tags:

views:

108

answers:

4
+11  A: 

Snippet 1 should be:

int *a = new int[6];
a[0]=1;

This is because a[0] is equivalent to *(a+0).

Cogwheel - Matthew Orlando
+1  A: 

You should just be using *a not (*a)[0].

Remember 'a' is a pointer. A pointer is an address.

*a = a[0] or the first integer
*(a + 1) = a[1] or the second integer

'a' is not a pointer to an array. It is a pointer to an integer. So, *a does not hand an array back to you for the [ ] to operate on.

What is confusing you is that the address of an integer array is also the address of the first integer in that array. Remember to always keep in mind the type of what you are assigning on the left hand side.

Consider the following:

int x = 10;

This snippet declares an integer x and assigns it the value 10. Now consider this:

int *y = &x;

This snippet declares that y is a pointer to an integer and it assigns the address of x to y.

You could write it this way:

int x = 10;
int *y;

y = &x;

By the way, when you assign something to 'y' above it will simply take the data at that address and turn it into an integer. So, if you send it a to an array of char (8 bits or 1 byte each) and an integer is 32 bits (4 bytes) long on your system then it will just take the first four characters of the char array and convert the resulting 32 bit number into an int.

Tread carefully with pointers, there be dragons here.

Justin
+1  A: 

It is ambiguous if a pointer points to an array or to a single item.

(*a) dereferences the first (or possibly only) item.

a[0] dereferences the first item.

a[1] explicitly treats the pointer as an array, and dereferences the second item. It is up to the programmer to ensure that such an item exists.

Will
+1  A: 

The indexing operator [] has a built-in * operator. So the first snippet is basically doing this:

int *a = new int[6];
*((*a) + 0) = 1;

So it dereferences once, which drops it to int, then adds zero (the index), then attempts to dereference again.

jdmichal