Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, Making a pointer to a char array

Tags:

c++

pointers

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?

like image 471
James MV Avatar asked Mar 12 '12 15:03

James MV


People also ask

Can a pointer point to an array?

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.

Can we use pointer as array in C?

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.


1 Answers

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;
like image 91
xanatos Avatar answered Sep 29 '22 05:09

xanatos