Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the address of elements in a char array?

I have a char array and I need to get the address of each element.

cout << &charArray

gives me a valid address, However if I try to get the address of a specific element, it spits out garbage:

cout << &charArray[0]
like image 737
Evan G Avatar asked Mar 01 '12 16:03

Evan G


2 Answers

std::cout << (void*) &charArray[0];

There's an overload of operator<< for char*, that tries to print the nul-terminated string that it thinks your pointer points to the first character of. But not all char arrays are nul-terminated strings, hence the garbage.

like image 113
Steve Jessop Avatar answered Oct 19 '22 19:10

Steve Jessop


You can do something like

&charArray + index * sizeof(char)
like image 1
Alecs Avatar answered Oct 19 '22 19:10

Alecs