Jojo Jonas
Jojo Jonas

Reputation: 223

C++ address handling (pointers)

I need to track my current location in a data buffer (which will be used as a packet), so I am using two variables, bufferLoc and dataBuffer.

char dataBuffer[8192];
char** bufferLoc;

I am pointing to the starting location of dataBuffer with bufferLoc. But incrementing bufferLoc does not affect its physical address in memory.

bufferLoc = (char**)&dataBuffer;

cout << &bufferLoc << endl;

bufferLoc++;

cout << &bufferLoc << endl;

These two prints will output the same location. Does my error have to do with type casting, with bufferLoc itself, or something completely different?

Thanks for your help.

Upvotes: 0

Views: 170

Answers (2)

perreal
perreal

Reputation: 98108

cout << &bufferLoc << endl;

prints the address of bufferLoc. This address is always the same. You can print the value stored in bufferLoc:

cout << bufferLoc << endl;

this value is the address of dataBuffer initially, when you increment it, it will be 4 bytes greater in the second print statement.

dataBuffer itself stores a pointer to a char array of 8192 bytes. What you want to do is to get this value:

char *bufferLoc = dataBuffer;

and increment this value. Note that type of bufferLoc is a pointer to a char array (just as dataBuffer). After assigning the address stored in dataBuffer to bufferLoc, you can print the first element: like this: cout << bufferLoc[0] << end.

Upvotes: 0

CuriousGeorge
CuriousGeorge

Reputation: 7400

If your intention is to scan through dataBuffer one byte at a time, then the second variable should be a pointer, not a pointer to a pointer.

char* bufferLoc;

then print it out without the ampersand:

cout << (unsigned int *)bufferLoc << endl;

note that cout will try to print your variable as text unless you cast to an unsigned int*

Upvotes: 2

Related Questions