RKapoor
RKapoor

Reputation: 9

C++ char pointers

I have a

*(char *) &data;

but need to send it as

(char *) &data;

Is there a difference between the two?

Added


Sorry for the confusion. I have two applications, first application in C that gives me *(char *) &data. On the receiving end (send over UDP) the C++ application expects the data as (char *) &data. I wanted to clarify if both the notion means the same or different


Upvotes: 0

Views: 541

Answers (3)

wallacer
wallacer

Reputation: 13213

This seems like very convoluted code.

As mentioned already, the first expression evaluates to a char& (editable reference to char) and the 2nd to a char*.

The first is a de-referenced pointer to a reference to a char. The second is a pointer to a reference to a char. Both seem like silly ways to be passing char data around to me. If you need to send an updatable reference, send &data which will be a pointer to your char data. If by send you mean pass into a method, you could also define the method as something like

void foo(char& inData) { ... }

in which case you could call

foo(data);

and the parameter inData inside of foo will be updated since it is a reference. Another option is

void foo(char* data) { ... }

in which case you would call

foo(&data);

This is a more pure C style approach, but I still use it fairly often in C++ because I find it more obvious that you're dealing with a reference to an object when it's explicitly declared as a pointer.

I'm not sure why you'd want to be dealing with things like *(char *) &data, and I'd venture to say it'd be bad practice to use that in your code since it makes your code less readable.

For more info on references and a comparison to pointers see here http://www.cprogramming.com/tutorial/references.html

Upvotes: 0

jmishra
jmishra

Reputation: 81

&data

This will provide the address of data variable. The pointer points to a chunk of memory location allocated to data.

(char *) &data

We then type cast the pointer to a character pointer - Effectively now the data is being interpreted as a stream of characters (1 byte at a time). So, still in memory it is the same address location, just that we want to interpret this memory chunk in a different way by typecasting. Finally,

*(char *) &data

gives you back the value at the memory location pointed by the pointer we got from above - that is the first byte of the memory.

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

Yes. There is a difference. The type of first expression is char& 1. The type of second expression is char*.

1. Thanks to Pete for the explanation why its char&, not char. Read the comments.

Upvotes: 4

Related Questions