BluPixel
BluPixel

Reputation: 13

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. 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]. 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

Upvotes: 0

Views: 2649

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

You allocate it just the same way you do the board arrays:

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++)
    {
        /* ... */
    }
}

Upvotes: 3

Related Questions