So, i was playing with C pointers and pointer arithmetic since i'm not entirely comfortable with them. I came up with this code.
char* a[5] = { "Hi", "My", "Name", "Is" , "Dennis"};
char** aPtr = a; // This is acceptable because 'a' is double pointer
char*** aPtr2 = &aPtr; // This is also acceptable because they are triple pointers
//char ***aPtr2 = &a // This is not acceptable according to gcc 4.8.3, why ?
//This is the rest of the code, the side notes are only for checking
printf("%s\n",a[0]); //Prints Hi
printf("%s\n",a[1]); //Prints My
printf("%s\n",a[2]); //Prints Name
printf("%s\n",a[3]); //Prints Is
printf("%s\n",a[4]); //Prints Dennis
printf("%s\n",*(a+0)); //Prints Hi
printf("%s\n",*(a+1)); //Prints My
printf("%s\n",*(a+2)); //Prints Name
printf("%s\n",*(a+3)); //Prints Is
printf("%s\n",*(a+4)); //Prints Dennis
printf("%s\n",*(*(aPtr2) +0)); //Prints Hi
printf("%s\n",*(*(aPtr2) +1)); //Prints My // ap = a, *ap = *a, *(ap)+1 = *a+1 ?
printf("%s\n",*(*(aPtr2) +2)); //Prints Name
printf("%s\n",*(*(aPtr2) +3)); //Prints Is
printf("%s\n",*(*(aPtr2) +4)); //Prints Dennis
char*** aPtr2 = &a
is not acceptable according to gcc 4.8.3, why?
Sorry forgot to add compiler warning:
warning: initialization from incompatible pointer type [enabled by default]
It maybe unclear what I'm trying to say, so I had to add this links:
Notice the commented out lines.
A triple-pointer is a pointer that points to a memory location where a double-pointer is being stored. The triple-pointer itself is just one pointer. Ex. int *** is a pointer, that points to the value of a double pointer, which in turn points to the value of a single pointer, which points to the value of an int.
2D array is NOT equivalent to a double pointer! 2D array is "equivalent" to a "pointer to row". The information on the array "width" (n) is lost.
array[3] . A pointer to pointer to type (double-pointer), is exactly what its name implies. It is a pointer, that holds a pointer as its value. In basic terms, it is a pointer that points to another pointer.
An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.
a
is the address of a buffer of 5 ptrs and is immutable (i.e. its a fixed ptr). If you allowed
char ***aPtr2 = &a;
then
*aPtr2 = &a[3];
would actually modify the address a
(which is verboten).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With