1

Possible Duplicate:
Is array name a pointer in C?

So, I usually declare arrays using pointers.

However, you can also declare arrays using square brackets notation:

char a[] = "ok" ;
char b[] = "to" ;
char *pa = a ;

cout << "a " << sizeof( a ) << endl ;   // 3
cout << "pa " << sizeof( pa ) << endl ; // 4

The peculiar thing is, sizeof( a ) will be the actual size of the array in bytes, and not the size of a pointer.

I find this odd, because where is the pointer then? Is a square bracket-declared array actually a kind of datastructure with (sizeof(char)*numElements) bytes?

Also, you cannot re-assign a to b:

a = b ; // ILLEGAL.

Why is that? It seems as though a is the array and not a pointer to the array ("left operand must be l-value" is the error for a = b above). Is that right?

Community
  • 1
  • 1
bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 1
    Dupe? http://stackoverflow.com/questions/1641957 Maybe not, because the confusion here perhaps is caused by the `char a[]` notation. @bobobobo, do you know that you can declare an array like `char a[3]`, and that will also be an actual array object, not a pointer? The empty brackets are just a shorthand because programmers can't count - `char a[] = "ok";` means the same as `char a[3] = "ok";` – Steve Jessop Apr 06 '11 at 17:25
  • I'd advocate using std::array in c++ if it is available to you. – shuttle87 Apr 06 '11 at 17:27

4 Answers4

5

Why is that? It seems as though a is the array and not a pointer to the array ("left operand must be l-value" is the error for a = b above).

a is indeed an array type and not a pointer type. You cannot assign to an array because it is a non-modifiable lvalue.

BTW Array decays to pointer to the first element when it is passed to a function.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
2

When you use the square brackets in your declaration, you are actually allocating space on the stack. When you use the * to declare a pointer, you are simply declaring a pointer. So

char a[] = "ok";

will actually allocate 3 bytes on the stack, and fill it with the string ok\0. However if you do

char a* = "ok";

it will allocate enough room for a pointer, and set the pointer to a location in the data section containing the string ok\0 (i.e. it's compiled in as a constant).

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
0

Correct, the type of a is char array of length 3. Array variables can be assigned to pointer variables because array types can decay into a pointer to the first element in the array.

Null Set
  • 5,374
  • 24
  • 37
0

In short, it's a constant pointer to the first (zeroth) element in the array.

Check out the "Pointers and Arrays" section here

holtavolt
  • 4,378
  • 1
  • 26
  • 40