1

I tried the following:

#include <stdio.h>

int main(void) {
     char multi[3][10];
     multi[0] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
     multi[1] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
     multi[2] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
     printf("&multi[2][2]: %d \n", (int) &multi[2][2]);
     printf("(*multi + 2) + 2: %d \n" , (int) (*multi + 2) + 2);
}

and yielded this output:

dominik@luna:~$ gcc tmp.c 
tmp.c: In function ‘main’:
tmp.c:5: error: expected expression before ‘{’ token
tmp.c:6: error: expected expression before ‘{’ token
tmp.c:7: error: expected expression before ‘{’ token

I already did some research and found this thread where Vladimir stated "You should initialize your arrays in the same line you declare them". This still leaves me confused, does that me you should not do it as in you should not write spaghetti code, or does it mean that you cannot do it.

Or could it be that I am doing something else completely wrong?

Community
  • 1
  • 1

1 Answers1

2

Arrays can be initialized, but not assigned, in this manner.

#include <stdio.h>

int main(void) {
     char multi[3][10] = {
         {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'},
         {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'},
         {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}
     }
     printf("&multi[2][2]: %d \n", (int) &multi[2][2]);
     printf("(*multi + 2) + 2: %d \n" , (int) (*multi + 2) + 2);
}

Also note that this will truncate the stack addresses that you print out, at least on 64-bit systems. Are you trying to print out stack addresses? Do this:

printf("&multi[2][2]: %p\n", (char *) &multi[2][2]);
printf("(*multi + 2) + 2: %p\n" , (char *) (*multi + 2) + 2);

On my system, this change will cause it to print the correct addresses, which are just under 247 (above 0x7fff00000000), which is out of the range of int.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • If they are _really_ stack addresses, then the truncation likely won't matter much for the purposes of printing. – John Dvorak Jan 05 '13 at 10:49
  • Agreed - but the low-order 32 bits are usually very good at distinguishing variables. That is, you don't start getting false duplicates before you start approaching the 4GB limit. – John Dvorak Jan 05 '13 at 10:55
  • @JanDvorak: Well, we're making assumptions here that we're using it to distinguish variables. And collisions are going to happen much sooner than 4 GiB due to the birthday paradox, depending on the allocation pattern, the phase of the moon, and ASLR. – Dietrich Epp Jan 05 '13 at 10:57