James MV
James MV

Reputation: 8717

C++, Making 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 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?

Upvotes: 9

Views: 72257

Answers (4)

xanatos
xanatos

Reputation: 111860

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;

Upvotes: 23

gettingSmarter
gettingSmarter

Reputation: 701

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

An example of what you are suggesting.

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

...

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

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

Upvotes: 1

CFL_Jeff
CFL_Jeff

Reputation: 2719

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

funcName(miniAlphabet);

and receive the array "by reference" like this:

void funcName(char *miniAlphabet) {
   ...
}

Upvotes: 1

Diego
Diego

Reputation: 18359

The position of the array in memory is the same as the position of its first element. So for example, both function signatures below are equivalent:

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

And you can call either version like this:

changeArray(miniAlphabet);

...or

changeArray(&(miniAlphabet[0]));

Upvotes: 2

Related Questions