On Sep 23, 2006, at 1:49 PM, Dave Smith wrote:

Grant Robinson wrote:
It depends on what you mean by "character array". If you are talking about a variable declared like so:

char myarray[32];

Then to get the address, you would do the following:

print("The address is %p\n", (&myarray));

If you are talking about a variable declared like:

char *myarray = new char[32];

Then the address is stored in 'myarray', and de-referencing 'myarray' will give you the actual contents of the string.


Wrong. In both cases (char* and char[]), the variable itself stores the address. You do not need the & operator in either case.

True, you do not NEED the operator. However, as illustrated below, using the & operator yields consistent results. Fundamentally, a 'pointer' holds an address to someplace else, and therefore it's address (the pointers location in memory) is not necessarily the same as the address of the data it points to. Non-pointer variables location in memory is the same as the address of the actual data. I will have to brush up on my CS 330 terminology if anyone wants to drill any deeper than that.


In fact, using the & operator is incorrect, because it will give you the address of the variable that was already holding the address of the character array, instead of the address of the character array.

False (at least with g++ 4.0.1). The following code snippet illustrates this:

#include <stdio.h>

int main(int argc, char **argv) {
    char array1[32];
    char *array2 = new char[32];

    printf("location of array1: %p\n", array1);
    printf("location of array2: %p\n", array2);
    printf("address of &array1[0]: %p\n", &(array1[0]));
    printf("address of &array2[0]: %p\n", &(array2[0]));
    printf("address of &array1: %p\n", &array1);
    printf("address of &array2: %p\n", &array2);
    delete[] array2;

    return 0;
}

Output on my machine:
location of array1: 0xbffff6fc
location of array2: 0x5002d0
address of &array1[0]: 0xbffff6fc
address of &array2[0]: 0x5002d0
address of &array1: 0xbffff6fc
address of &array2: 0xbffff6f8

What this says to me:
array1 == (&(array1[0])) == (&array1)

array2 == (&(array2[2]))

but

array2 != (&array2)

(parentheses are for clarity and/or to make Scheme and Lisp lovers more comfortable)

:)

Grant


/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/

Reply via email to