c++ question

Dave Smith dave at thesmithfam.org
Sun Sep 24 22:04:48 MDT 2006


Grant Robinson wrote:
> 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)
>
> :)


Look, the original poster just wanted to know how to print the address 
of a character array. You just demonstrated that using the & operator 
with array2 gives you the WRONG answer, which was my point originally, 
so I stand behind my original argument in the context of the OP's 
question. I wasn't saying that the & would never work, just that the OP 
shouldn't use it to solve this problem. Your code defends that argument 
pretty well.

By the way, the best answer was already given days ago with a simple 
printf( "%p\n", var ), which I'm sure worked just fine without all the 
pedantic ramblings about the intricacies of & and why C++ is so evil and 
such (which I have thoroughly enjoyed). I sure hope the OP has moved on 
to bigger and better problems to solve.

Lastly, to provide another answer to the poster without using printf(), 
you could use cout in combination with a cast to get the answer like so:

   char *array = "foobar";
   cout << "The address is 0x" << hex << (unsigned int)array << endl;

Which also works just fine and does not use the & operator. This is 
mostly for people who dislike including system headers that end with 
".h". :)

--Dave

P.S. I happen to think C++ is a great language, and I use it in lots of 
new projects all the time. I work with several hundred other people who 
do the same thing. I've never run into a bug that was *caused* by a 
deficiency in C++ that could not have been easily reproduced in other 
languages. C++ is just fine for me. This from a person who has written 
lots of Java, PHP, Python, and Perl code (and even a tiny bit of Scheme).



More information about the PLUG mailing list