C ++, creating a pointer to a char array

In C ++, I have a char array defined as:

char miniAlphabet[] = {'A','B','C','D','E', '\0'};

I want to change the values ​​of this array from other functions without passing them to these functions. This is where you use pointers correctly?

So my question is the right way to make a pointer to this char array. I would just point to the first element, and then when I want to change the values, I go through memory until I find the end character?

+5
source share
4 answers
char miniAlphabet[] = {'A','B','C','D','E', '\0'};

They are equivalent.

char *p1 = miniAlphabet;

char *p2 = &(miniAlphabet[0]);

Note that they are ()useless for operator precedence, therefore

char *p3 = &miniAlphabet[0];

In C / C ++, the name of the array is a pointer to the first element of the array.

Then you can use math pointers to do the magic ...

This points to the second element:

char *p4 = &miniAlphabet[0] + 1;

char *p5 = &miniAlphabet[1];

char *p6 = miniAlphabet + 1;
+14

. , , :

function changeArray(char[] myArray);
function changeArray(char* myArray);

:

changeArray(miniAlphabet);

...

changeArray(&(miniAlphabet[0]));
+1

If you pass an array to a function, you ARE pass by reference as an array variable, actually just a pointer to the address of the first element in the array. So you can call a function like this:

funcName(miniAlphabet);

and get the array "by reference" as follows:

void funcName(char *miniAlphabet) {
   ...
}
+1
source

In short, yes. When you create an array, miniAlphabet is a pointer to an array of size and type that you defined. It is also a pointer to the first element.

An example of what you offer.

void foo(char *array)
{
    array[0] = 'z';
    array[2] = 'z';
}

...

char myArray[] = { 'a', 'b', 'c'};
foo(myArray);
//myArray now equals  {'z', 'b', 'z'}

also note, dereferencing myArray gives you a value in the first element.

+1
source

All Articles