In some code that I read, there was an initializing statement like this
char *array[]= { \"something1\", \"something2\", \"something3\" };
what that means ?
It's initializing an array of strings (char *
) with three values (three pointers to null-terminating strings)
and what that pointer points to ?
It should point to the first element in the char*
array
how is that allocated in memory ?
It will allocate enough memory to store the three strings followed by null-terminators, as well as the three pointers to those strings:
array --> pointer to three sequential memory addresses
array[0] --> something1{\0}
array[1] --> something2{\0}
array[2] --> something3{\0}
Note that the strings may not necessarily be in sequential memory
and how can I access every element
if by "element" you mean the string, you can loop though the pointers:
for(int i=0; i<3; i++)
{
char* element = array[i];
}
and every character of an element in that array
well, you could access the chars using array syntax (element[i]
) but I would recommend using the C string functions for safety (so you don't have to worry about accessing memory outside the range of the string)