0

I have the following error expected ':', ',', ';', '}' or 'attribute' before '=' token

struct arrap{
 char p[6][6] = {
    {' ',' ',' ',' ',' ',' '},
    {' ',' ',' ',' ',' ',' '},
    {' ',' ',' ',' ',' ',' '},
    {' ',' ',' ',' ',' ',' '},
    {' ',' ',' ',' ',' ',' '},
    {' ',' ',' ',' ',' ',' '}
    };
};

it seems that it doesnt work any other ways to initialize the values of the 2d array inside a structure?

PNC
  • 347
  • 1
  • 5
  • 17

3 Answers3

3

This is the correct way:

struct arrap {
     char p[6][6];
} a = {{{' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' '},
        {' ',' ',' ',' ',' ',' '}
      }};

It declares the type struct arrap and declares an object a of type struct arrap with the initializers you wanted.

You cannot set default initializer values for a type in C but you can initialize an object at declaration time.

ouah
  • 138,975
  • 15
  • 262
  • 325
  • it answered my question but int main(){ int x,i; struct arrayp p; for(i = 0;i<5;i++){ for(x = 0; x<5;x++){ printf("%c\n",p.p[i][x]); } } it prints characters that is not ' ' why is it? – PNC Dec 15 '13 at 16:12
  • @PNC except that you have to use `6` instead of `5` in your loops, this looks fine to me. Remember that `' '` are white spaces. Otherwise, please show the whole program. – ouah Dec 15 '13 at 16:18
2

You can't assign to an array inside a structure. You have to initialize it when you create an instance of the structure.

The easiest way is probably to have a constant static array, and use e.g. memcpy to copy it:

static const char p_template[6][6] = { ... };

...

struct arrap ap;
memcpy(ap.p, p_template, sizeof(p_template));
Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
1

Quick & Dirty:

struct arrap s;
memset(&s, ' ', sizeof(s.p));

This works as the address of the 1st member of a struct is guaranteed to be the same address of the struct itself.

alk
  • 68,300
  • 10
  • 92
  • 234