tags:

views:

132

answers:

5

I have the following variables:

char *p;
int l=65;

Why do the following casts fail?

(int *)p=&l;

and:

p=&((char) l);
+4  A: 

The correct way to do this would be:

int I = 65;
char* p = (char*)&I;

&I gives you an int* that points to I; you then cast this to a char* and assign it to p.

Note that you shouldn't ordinarily cast between pointers of unrelated types. A char* can be used to access any object, though, so in this particular case it is safe.

James McNellis
Specifically, according to C99 6.3.2.3.7, the behaviour of converting a pointer of one type to a pointer of a different type is undefined only if the pointers in question have different alignments. It continues to say that when a pointer to an object is converted to a pointer to character type, the result points to the lowest addressed byte of the object.
dreamlax
@dreamlax: Actually, I was thinking of C99 §6.5/7, which details the aliasing rules. Converting pointers may not lead to undefined results, but accessing the pointed to object might.
James McNellis
A: 

In plain C, which is not that strict to type conversions, this code would compile and actually work. On a C++ compiler it would actually require explicit casts as already mentioned (see other answers).

Kotti
caf
Hm. I don't know why, but msvs2008 compiles this code and the debug shows that it actually works. Strange.
Kotti
+4  A: 
Michael Aaron Safyan
+7  A: 

The result if type conversion is always an rvalue. Rvalue cannot be assigned to, which is why your first expression doesn't compile. Rvalue cannot be taken address of, which is why your second expression doesn't compile.

In order to perform the correct type conversion, you have to to it as follows

p = (char *) &l;

This is the proper way to do what you tried to do in your second expression. It converts int * pointer to char * type.

Your first expression is beyond repair. You can do

*(int **) &p = &l;  

but what it does in the end is not really a conversion, but rather reinterpretation of the memory occupied by char * pointer as int * pointer. It is an ugly illegal hack that most of the time has very little practical value.

AndreyT
hey idont understand your typing (int **) ,,,,what meaning has (int **)
gcc
Pointer-to-pointer. As stated in that answer, it's just an ugly trick.
Kotti
thanks for help
gcc
A: 

The problem is that when you're performing the casts (aside from whether or not the kind of casting you're doing is a good idea or not) is that the cast expression results in an rvalue.

rvalues cannot be assigned to or have their addreses taken.

Michael Burr