0

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.

3
  • Yes, that is, in this case 3 char + null char Commented May 16, 2012 at 13:42
  • C is like chinese to me isn't this a top phrase for IT college drop-outs? Commented May 16, 2012 at 13:49
  • I dont know, my friends all graduated :( Commented May 16, 2012 at 14:06

5 Answers 5

2

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]
Sign up to request clarification or add additional context in comments.

5 Comments

So the { "OFF", "ON", "IL1", "IL2" } part just "labels" the "rows" of the array?
They are the content of the array.
So, since they are all 3- char- content, char state [4][3] would have been sufficient, right?
no. Note that I added \0 at the end of each word, as in C string there is another hidden character, \0, called the null terminator that signals the end of the string, and you need to have space for it too. en.wikipedia.org/wiki/Null-terminated_string
You welcome. It's a little bit confusing at the beginning but it gets easier :)
2

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

Comments

2

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.

Comments

0

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].

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.