initializing array values upon declaration
I want to load 9 predetermined strings and 8 predetermined integers to two different arrays. I have seen code of the form:
Code:
char *namelist[] = {"Ram", "Shyam", "Dhyaan",};
int numlist[] = {0, 1, 4, 2, 5, 3, 6, 11,};
But I want to know some things:
- what is the * for in the first statement?
- since a string is already a character array and I need to create an array of strings, don't I need to write char *namelist[][] (two []-s)?
- is the comma necessary before the closing brace?
- is the semicolon necessary after the closing brace?
Re: initializing array values upon declaration
Quote:
Originally Posted by jamadagni
what is the * for in the first statement?
namelist is an array of strings and strings in C are of char * type.
Quote:
Originally Posted by jamadagni
don't I need to write char *namelist[][] (two []-s)?
No, futhermore you can't declare a multidimentional array without specifying dimentions.
Code:
int wont_work[][] = { {1,2,3}, {4,5,6} }; // error
int will_work[][3] = { {1,2,3}, {4,5,6} };
Quote:
Originally Posted by jamadagni
is the comma necessary before the closing brace?
No.
Quote:
Originally Posted by jamadagni
is the semicolon necessary after the closing brace?
Yes.
Re: initializing array values upon declaration
Quote:
Originally Posted by jacek
strings in C are of char * type.
Do I read that as "strings in C are of the nature of pointers to char-length memory spaces"?
Quote:
futhermore you can't declare a multidimentional array without specifying dimentions.
Code:
int wont_work[][] = { {1,2,3}, {4,5,6} }; // error
int will_work[][3] = { {1,2,3}, {4,5,6} };
How come you still don't need to specify the first dimension? And if I declare char *namelist[] and include lots of strings should it not be mandatory that I specify the second dimension - i.e. the maximum length of strings?
Re: initializing array values upon declaration
Quote:
Originally Posted by jamadagni
Do I read that as "strings in C are of the nature of pointers to char-length memory spaces"?
Yes.
Quote:
Originally Posted by jamadagni
How come you still don't need to specify the first dimension?
It's one of those inconsistencies and in fact arrays are evil.
Quote:
Originally Posted by jamadagni
And if I declare char *namelist[] and include lots of strings should it not be mandatory that I specify the second dimension - i.e. the maximum length of strings?
Because you declare an array of pointers, not a two dimensional array.
Re: initializing array values upon declaration
Quote:
Originally Posted by jacek
Isn't that because you provide the dimension of the array right in the assignment? And furthermore, is that a standard or a compiler extension to allow such a declaration and assignment statement?
Re: initializing array values upon declaration
Quote:
Originally Posted by wysota
is that a standard or a compiler extension to allow such a declaration and assignment statement?
K&R use that form of assignment in their book.