Re: Array of char pointers. by Alex
Alex
Sun Apr 13 12:27:38 CDT 2008
"goodTweetieBird" wrote:
> If I had to say what "arr" is, I would say it is an array of
> pointers to chars. If so why is it intialized with strings
> instead of addresses?
First of all, `arr' a an array of pointers to const chars. VC++
compiler allows you to assign a pointer to const char to non-const
pointer as a backward compatibility with older versions of the
compiler:
char* p = "Hello World!"; // compiles, but dangerous
// no diagnostics at compile time,
// but an access violation exception at run-time
p[3] = 'z'; // boom!
Also, you should remember that intializing a [const] pointer to
char from literal strings is no more than a courtesy of the
compiler, which is provided for developer's convenience. So, this
initialization:
const char* p = "hello";
is actually translated into this:
const char __tmp[] = { 'a', 'b', 'c', '\0' };
// array type decays to pointer type
const char* p = __tmp;
One can safely assume that `__tmp' address will stay valid for the
duration of a program because actual string data is stored in data
section of an executable image.
> char *arr[] =
> {
> "a", "b", "c","dd", "eee"
> };
>
> Also when looking at the values of the pointers (when they
> appear to be adjacent) they seem to decrease by at least 8 bytes
> ( two native size words?) even when the strings are a single
> character, which should be two bytes. So I am guessing they are
> on a stack if the addresses decrease but why 8 bytes each?
No, they aren't on stack. They're stored permanently in the data
section of an executable image. The addresses of the strings are
not required to be adjacent at all. Compiler may put them in
whatever order and at whatever locations it pleases in the data
section. Moreover, compiler may decide to coalesce similar strings
to save space, so in the following code:
const char* arr[] = { "abc", "abc", "abc" };
all three elements of the `arr' array will hold the same value:
assert(arr[0] == arr[1] == arr[2]);
> Is it some type of linked list? I suppose it doesn't really
> matter but it is a curiosity and I am interested in how the
> language works.
No, they aren't linked list or any data structure at all. Compiler
puts string literals in data section and even may enable
optimizations to save space.
HTH
Alex