In C++, I have a char array defined as:
char miniAlphabet[] = {'A','B','C','D','E', '\0'};
I want to modify the values of this array from other functions without passing it to those functions. This is where you use pointers right?
So my question is what is the correct way to make a pointer to this char array. Would I just make a pointer to the first element and then when I want to modify the values I step through memory until I hit the end character?
Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.
Master C and Embedded C Programming- Learn as you go Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers.
char miniAlphabet[] = {'A','B','C','D','E', '\0'};
These are equivalent.
char *p1 = miniAlphabet;
char *p2 = &(miniAlphabet[0]);
Note that the ()
are useless for the operators' precedence, so
char *p3 = &miniAlphabet[0];
In C/C++ the name of an array is a pointer to the first element of the array.
You can then use pointers' math to do some magic...
This will point to the second element:
char *p4 = &miniAlphabet[0] + 1;
like
char *p5 = &miniAlphabet[1];
or
char *p6 = miniAlphabet + 1;
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