Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in C struct

Tags:

arrays

c

struct

I want to have two arrays in a struct, which are initialized at start but need editing further on. I need three instances of the struct, so that I can index into a specific struct and modify as I wish. Is it possible?

This is what I thought I could do but I get errors:

struct potNumber{
    int array[20] = {[0 ... 19] = 10};
    char *theName[] = {"Half-and-Half", "Almond", "Rasberry", "Vanilla", …};
} aPot[3];

Then I access the structs as follows:

 printf("some statement %s", aPot[0].array[0]);
 aPot[0].theName[3];
 …
like image 653
Greg Avatar asked Mar 02 '11 16:03

Greg


1 Answers

The struct themselves do not have data. You need to create objects of the struct type and set the objects ...

struct potNumber {
    int array[20];
    char *theName[42];
};

/* I like to separate the type definition from the object creation */
struct potNumber aPot[3];
/* with a C99 compiler you can use 'designated initializers' */
struct potNumber bPot = {{[7] = 7, [3] = -12}, {[4] = "four", [6] = "six"}};

for (i = 0; i < 20; i++) {
  aPot[0].array[i] = i;
}
aPot[0].theName[0] = "Half-and-Half";
aPot[0].theName[1] = "Almond";
aPot[0].theName[2] = "Rasberry";
aPot[0].theName[3] = "Vanilla";
/* ... */

for (i = 0; i < 20; i++) {
  aPot[2].array[i] = 42 + i;
}
aPot[2].theName[0] = "Half-and-Half";
aPot[2].theName[1] = "Almond";
aPot[2].theName[2] = "Rasberry";
aPot[2].theName[3] = "Vanilla";
/* ... */
like image 141
pmg Avatar answered Sep 19 '22 15:09

pmg