简体   繁体   English

C编程-初始化2D结构数组

[英]C Programming - Initializing a struct 2D array

Okay so I'm trying to pass elements of a 2D array with string elements to a 2D array in struct. 好的,所以我试图将带有字符串元素的2D数组的元素传递给struct中的2D数组。 I made a code, but it receives a run-time error. 我编写了代码,但是收到运行时错误。 I think there's a problem in the code where I'm trying to initialize board2[i][j]. 我认为我尝试初始化board2 [i] [j]的代码中存在问题。 Any help is appreciated. 任何帮助表示赞赏。

  char ***board;
  int i, j, size;

  printf("Enter the size of array:");
  scanf("%d", &size);

  if((board = (char***)malloc(sizeof(char**)*size))==NULL)
  {
       printf("Memory Allocation failed\n");
       return -1;
  }

  for(i=0; i<size; i++)
  {
       if((board[i] = (char**)malloc(sizeof(char*)*size))==NULL)       
       { 
          printf("Memory Allocation failed\n");
          return -1;
       }
       for(j=0; j<size; j++)
       {
          if((board[i][j] = (char *)malloc(sizeof(char)*4))==NULL)
          {
            printf("Memory Allocation failed\n");
            return -1;
          }
          a = rand() % 2;  
          b = rand() % 2;
         if(a==0 && b==0)
            strcpy(board[i][j], "ab");
         else if(a && b==0)
            strcpy(board[i][j], "Ab");
         else if(a==0 && b==1)
            strcpy(board[i][j], "aB");
         else
            strcpy(board[i][j], "AB");
        }

  struct data{
    const char *element;
    int visited;
  };    
  void board2_initialize(char ***board, int size)
  {
  struct data **board2;


  for(i=0;i<size;i++)
  {
    for(j=0;j<size;j++)
    {
     board2[i][j].element = board[i][j];
     board2[i][j].visited = 0;
     printf("%s", board2[i][j].element);
    }
  }
  }

EDIT: Forgot to mention that the initialization will occur inside a function 编辑:忘记提及初始化将在函数内进行

You allocate it just the same way you do the board arrays: 您可以像分配board阵列一样分配它:

struct data **board2 = malloc(sizeof(struct data *) * size);

for(i = 0; i < size; i++)
{
    board2[i] = malloc(sizeof(struct data) * size);

    for(j = 0; j < size; j++)
    {
        /* ... */
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM