Initialize. Typo.
The
"Hello"
is
Const Data. See
http://www.gotw.ca/gotw/009.htm
p[1] = new char [42] {"world"};
p[2] holds the address of a character pointer which further points to array of 42pointers---right can I latter change it from 42 to 70 or something |
No. p[1] is a pointer. That pointer has the address of a memory block that has been allocated from Free Store and is large enough to contain 42 characters.
A resize is not possible, but one can deallocate current and allocate new:
1 2
|
delete [] p[1];
p[1] = new char [70];
|
I think I had a syntax error on the array initialization.
1 2 3 4 5
|
char a1[] = "Dolly";
char a2[] = {'D', 'o', 'l', 'l', 'y', '\0'};
char a3[] {'D', 'o', 'l', 'l', 'y', '\0'};
char a4[6];
strcpy(a4, "Dolly");
|
C-string:
The convention used by "string" functions in C is that a string is a null-terminated char array. The a2, a3, and a4 above show explicitly that there are 6 characters in "Dolly". The strlen("Dolly") returns 5.
The p[3] is a
char*
and therefore a statement like
cout << p[3];
will assume that p[3] points to a C-string and will print characters from consecutive bytes until a '\0' is encountered. However, we did set the p[3] to point to the byte that holds value of X and we have no idea whatsoever what will be in the next bytes during runtime.
That p[3] is an example of "valid" syntax that is most likely logically utterly, horribly wrong, unexpected, etc.
Do I have to explicitly note that the p was an array of 7 pointers, but my example initialized only 4 of them and thus the 3 last pointers are still invalid?
C++ standard library has
std::string
,
std::vector
, etc so that you would not need to use
new
,
delete
, arrays, C-strings, pointers, etc for
mundane things.