fweigl
fweigl

Reputation: 22018

C Char multidimensional Array Definition

C is like chinese to me but i got to work with some code

struct Message {
    unsigned char      state;
};

char state   [4][4] = { "OFF", "ON", "IL1", "IL2" };

This is a simple server that receives a message. The Struct part of it is obvious, but then theres that char array thing. Does this say theres 4 different char arrays, each containing 4 chars? What exactly is going on here? I know this sounds stupid but I cant figure it out.

Upvotes: 0

Views: 284

Answers (5)

NPE
NPE

Reputation: 500317

Does this say theres 4 different char arrays, each containing 4 chars?

That's exactly right: state is an array of four char sub-arrays.

Each sub-array is four chars long. The corresponding string literal ("OFF" etc) is padded with NULs to four characters, and copied into the sub-array.

Upvotes: 2

Julien
Julien

Reputation: 155

It's a two-dimensional array. It creates an array of 4 elements, each of which is an array of 4 char.

Upvotes: 2

eboix
eboix

Reputation: 5133

In C, you deal with strings as char*, or arrays of char. Therefore, when you have an array of strings, you have an array of an array of chars.

Upvotes: 0

Jayan Kuttagupthan
Jayan Kuttagupthan

Reputation: 550

char state[4][4] declared at the end is a 2 dimensional array having 4 rows with 4 columns in each row. The values you have assigned will be stored into positions state[0][0], state[0][1], state[0][2], state[0][3].

Upvotes: 0

MByD
MByD

Reputation: 137312

It means that state is an array of 4 char arrays, each of them is an array of 4 char, and they are initialized with the values "OFF\0", "ON\0", "IL1\0" and "IL2\0"

         +----+----+----+----+
state => |OFF |ON  |IL1 |IL2 |
         +----+----+----+----+
         ^state[0]
              ^state[1]
                   ^state[2]
                        ^state[4]

Upvotes: 2

Related Questions