why doesn’t this work:
Snippet 1:
int *a = new int[6]; (*a)[0]=1;
while this is working
Snippet 2:
int myint = 0; int *ptr = &myint; *ptr=1;
I know that if i use a[0]=1 in snippet 1 it will work. But for me that makes no sense, cos for me it looks that a[0]=1 means: put value 1 to adress a[0]. In other words I put the value as the memory. Instead it makes more sense to use (*a)[0]=1 which means to me: put value 1 to the value field which a[0] points to.
Could anyone describe this discrepance?
You should just be using *a not (*a)[0].
Remember ‘a’ is a pointer. A pointer is an address.
‘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:
This snippet declares an integer x and assigns it the value 10. Now consider this:
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:
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.