How to create an array of c style string?

Jul 17, 2014 at 3:42am
Hey,guys, I just read from a textbook saying that you can actually create an array of c style string like this:

 
  char *stringArray[] = {...}

which baffled me a lot. As I read this syntax, it should be defining an array of pointers pointing to characters. How should I correctly interpret this syntax?
Jul 17, 2014 at 4:11am
That's pretty much it.
Jul 17, 2014 at 7:10am
That's pretty much it.

Thanks for replying, but I still don't get it. Are you saying that an array of pointers pointing to characters is the same thing as an array of c style strings?
Jul 17, 2014 at 7:15am
It's more an array of char pointers pointing to arrays of chars. An array of chars being a c style string.
Jul 17, 2014 at 7:20am
What I'm saying is that a pointer to a character is the same thing as a pointer to an array of characters, which itself may be a C style string. Some arrays of characters are not C style strings, although all C style strings are arrays of characters.
Jul 17, 2014 at 7:30am
Good distinction. It crossed my mind to say that, but I didn't for some reason.
Jul 17, 2014 at 8:17am
Or in other words:
We do know that T * p; is a pointer. Pointer holds an address. In that address is supposedly an object of type T. The following addresses p + N*sizeof(T) might contain other objects of type T, but we have no way to be sure (unless we can see from the code that it is so).

There is no difference between pointer to single object and pointer to array. Furthermore, a pointer can be used as an iterator, which does not "own the memory", like the other uses.

C-style string is an array of characters that contains a null character to indicate the end of the array. The string can be stored in character array that is longer than the string.
For example: char foo[256] = "Hello"; // We fill only 6 chars: { 'H','e','l','l','o','\0' }


The ellipsis in this example can have much fun.
char *stringArray[] = {...}
1
2
3
4
5
6
7
8
9
10
char foo[] { "Hello" }; // local array, 6 elements, contains a C-string
char *bar = new char [6] {}; // dynamic array, 6 elements, contains a C-string (all chars are nulls)
char gaz {'F'}; // a local character, not a C-string

char *stringArray[] { foo, bar, &gaz, "world", foo+1 };
// stringArray[3] points to a C-string literal constant, which are read only
// cout << stringArray[4]; shows "ello"
// cout << *stringArray[2]; shows "F"
// cout << stringArray[2]; shows something that starts with 'F',
//    but who knows how may bytes more you see before a null? 

Obviously, you would never create such a mess; you want each pointer to have "same logical type".
Furthermore, the references to literal consts should be const: const char * words { "Hello", "world" };
Jul 21, 2014 at 3:23am
To helios, Yay295 and keskiverto:
Profuse thanks to guys! Your replies really helped me a lot!!!
Topic archived. No new replies allowed.