Peeter Joot's Blog.

Math, physics, perl, and programming obscurity.

Posts Tagged ‘array address’

Address of an array base. What was the C language designer smoking?

Posted by peeterjoot on June 8, 2010

I regularly see code that grabs the address of the first element in an array in different ways. Some made up examples:

void bar( char * ) ;

void foo
{
   char x[3] ;

   bar( x ) ;
   bar ( &x ) ;
   bar( &x[0] ) ;
   bar( (&x[0]) ) ;
}

Sometimes these get really complex looking when the array element is in some nested structure and the coder in question is so unsure about how to get the first element address that lots of extra braces are tossed in.

It’s worthwhile demonstrating to oneself that these are all identical. Something like the following does the job:

#include <stdio.h>

int main()
{
   char x[3] ;

   printf("%p %p %p\n", x, &x, &x[0] ) ;

   return 0 ;
}

What I have to wonder about something like this is why would the language allow both x and &x as equivalent syntax? Is it so counterintuitive to have x == &x, but this is actually true in this case! Even though I’ve seen it time and time again, the &x syntax seems to be much less common than just x or &x[0], and it throws me off when I see it.

I get the rough impression, at least from our code, that the &x[0] form is generally preferred. I’d infer from this that is it not obvious to many that just plain x is the array base address, and thus the address of the first element.

Posted in C/C++ development and debugging. | Tagged: , , | 6 Comments »

 
Follow

Get every new post delivered to your Inbox.