Home > other >  Array of arrays of structs
Array of arrays of structs

Time:05-29

I have to statically allocate a struct. It represents a row of a file.

typedef struct file_row {
  char lat[MAXCHAR];
  char lot[MAXCHAR];
  char noise[MAXCHAR];
} file_row_t;

I have to create an array of those structs so:

typedef file_row_t file_rows[NUMBER_OF_ROWS];

I have to create an array of those array of structs, so:

typedef file_rows array_file_row_t[NUMBER_OF_FILE];

To statically allocate it, I tried:

static file_rows file_entry_1[] = {
{ "5.83613506988462", "7.517027380149415", "17.8638534936465" }
, { "1.00316872133421", "6.081590272977937", "0.3844105125918" }
, { "4.55349057609303", "5.608649972060196", "5.9341717073556" }};

To statically create an array with all those files, I tried:

static array_file_row_t files[] = { file_entry_1, file_entry_2, file_entry_3 };

To get a single file entry I tried:

file_rows file[] = files[node_id];

To get a single row of this file I tried:

file_row_t row = file[file_pos];

The problem is that I got multiple errors during the compilation: If it can helps I paste it here:

region_data.h:22:1: error: missing braces around initializer [-Werror=missing-braces]
{ "5.83613506988462", "7.517027380149415", "17.8638534936465" }
 ^
region_data.h:2027:35: note: (near initialization for 'file_entry_3')
region_data.h:3030:37: error: initialization makes integer from pointer without a cast [-Werror=int-conversion]
static array_file_row_t files[] = { file_entry_1, file_entry_2, file_entry_3 };
region_data.h:3030:37: note: (near initialization for 'files[0][0][0].lat[0]')
region_data.h:3030:37: error: initializer element is not computable at load time
region_data.h:3030:37: note: (near initialization for 'files[0][0][0].lat[0]')
region_data.h:3030:51: error: initialization makes integer from pointer without a cast [-Werror=int-conversion]
static array_file_row_t files[] = { file_entry_1, file_entry_2, file_entry_3 };
                                               ^

CodePudding user response:

#define MAXCHAR 256
#define NUMROWS 12
#define NUMFILE 8

typedef struct row {
  char lat[MAXCHAR];
  char lot[MAXCHAR];
  char noise[MAXCHAR];
} row_t;

typedef row_t row_list_t[NUMROWS];

typedef row_list_t file_list_t[NUMFILE];

int main(void)
{
  file_list_t files;

  for(int i = 0; i < NUMFILE;   i) {

    for(int j = 0; j < NUMROWS;   j) {

      sprintf(files[i][j].lat, "Lat: %d", i * j);
      sprintf(files[i][j].lot, "Lot: %d", i * j);
      sprintf(files[i][j].noise, "Noise: %d", i * j);

    }
  }
}

CodePudding user response:

{ file_entry_1, file_entry_2, file_entry_3 }

This is NOT an array of file_rows. This is an array of pointers to file_rows.

file_entry_1, file_entry_2 and file_entry_3 are pointers.

  •  Tags:  
  • c
  • Related