c - 如何使用 typedef 结构创建带有随机数的矩阵?

标签 c

我正在尝试编写一个函数,该函数创建一个包含随机分布的 1 和 0 的矩阵,但出现错误:预期标识符位于数字常量之前。

有人可以给我一些关于我做错了什么的指示吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 7
#define COLUMNS 7

typedef struct {
const int rows;
const int columns;
int board[ROWS][COLUMNS];
} game;

void newGame(game *session);

int main(void){

game session = {ROWS, COLUMNS};

 srand(time(NULL));

return 0;
}

/* Function:    newGame
 * Description: Set up a new game with random states for each brick.
 * Input:       A pointer to the game structure.
 * Output:      The game structure pointed to is updated.
 */
void newGame(game *session){

for(int r = 0; r<ROWS; r++){
    for(int c = 0; c<COLUMNS; c++){
        session[r].ROWS = rand()%2;
        session[c].COLUMNS = rand()%2;
    }
  }
 }

最佳答案

这个:

session[r].ROWS = rand()%2;

没有任何意义,session是指向单个游戏的指针,而不是数组,ROWS是一个#define 此处将替换为整数。

您的意思可能是:

session->board[r][c] = rand() % 2;

此外,您对大小的处理相当困惑,它既是常量,又是运行时可读的。我不确定这对我来说完全有意义,但也许出于某种原因它很方便。

关于c - 如何使用 typedef 结构创建带有随机数的矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384011/

相关文章:

c - 在c程序中确定以太网帧到达时间的最准确方法

c - 执行USB/Pendrive中编译的C

自定义堆/内存分配范围

Char 数据类型在两个字节的情况下保持\n

c++ - 一次从套接字读取 1 个字节与读取大块

c - 在 C 中的结构上使用 malloc 后,数组中的默认值是多少

java - JNI : convert Primitive type to jobject Or SetObjectArrayElement of Object type after casting

c - "ar_ptr = arena_for_chunk(p);"是什么意思?

c - 我的程序卡在 c 中的 do,,while 循环中

c - 什么类型的字符串是 C 字符串函数的合法输入?