views:

59

answers:

4

Hello, I am making my first C program, and it utilizes a 2D array, and the code seems weird to me. First, why do I have to store "White" in [1][6]? I tried [0][6], but the compiler complains and won't run but when I call it in printf, it's [0][6]. Also, when trying to store "Bl" in codes [2][6], it says conflicting type for codes. Any help would be appreciated, thanks.

int main (int argc, const char * argv[]) {

 for (q=0; q<=457; q++) {
  for (w=0; w<=6; w++) {
   codes[q][w] = 0;
  }
 }

 char codes[1][6] = {'W','h','i','t','e','\0'};
 char codes[2][6] = {'B','l,'\0'};

 printf("%c\n", codes[0][0]);
A: 
  1. You cant initalize array [0][6] beucase this is a vector, and first index dont have elements.
  2. And you cant 1D (vector) array assign to 2D array. {'W','h','i','t','e','\0'} and {'B','l,'\0'} is a 1D array like a something[6] or in second case something[3].
  3. And you have triple declaration of codes variable. You can only one declare variable.
Svisstack
+5  A: 

You are confusing two tasks that you need to perform. One task is to declare a variable, and tell the compiler what type it's going to hold. The second task is to put data into it.

You are doing both tasks at the same time, and this is confusing you. In your first statement you are telling the compiler, "codes is a 2-dimensional, 1x6 array. By the way, here are the values to put into it: "White"." Your second sattement says, "codes is a 2-dimensional, 2x6 array. By the way, put "BI" into it."

The compiler is complaining and saying, "It can't be a 2x6 array, becuase you already told me it's a 1x6 array."

What you need is something like this:

char codes[2][6] = { {'W','h','i','t','e','\0'}, {'B','l,'\0'} };

You would then get your 'W' by looking at codes[0][0], etc.

jwismar
A: 

Instead of codes[0][6] if you want the compiler to decide the size of array depending on your initialization, you could say:

char codes[][6] = {'W','h','i','t','e','\0'};

if you're trying to initialize 2D array:

Try:

char codes[2][6] = {{'W','h','i','t','e'}, {'B','l'}};

Or

char codes[][6] = {{'W','h','i','t','e'}, {'B','l'}};
Dave18
A: 

You're confusing initialization with assignment. You can either initialize the array when you declare it, as in

char codes[N][6] = { // where N is the total number of codes
  "White", // assigns codes[0][0] - codes[0][5] as 'W','h','i','t','e',\0
  "Bl",    // assigns codes[1][0] - codes[1][2] as 'B','l',\0
  ...
}; 

which is equivalent to writing

char codes[N][6] = {
  {'W','h','i','t','e',\0},
  {'B','l',\0},
  ...
};

or you can assign elements of the array after the declaration, as in

char codes[N][6];
...
strcpy(codes[0], "White"); 
strcpy(codes[1], "Bl");
...

What you've done is munged the two together, so you're redeclaring codes with different types (the compiler is interpreting your use of [0][6] and [1][6] as array sizes, not locations), hence the compiler errors.

John Bode