Re: why does 'a' change?




spi...@xxxxxxxxx wrote:

yusufm@xxxxxxxxx wrote:

Hi,

For the following program:

char* ptr;
int a = 65;
ptr =(char*) &a;



cout << "ptr: " << (unsigned int) ptr << "\n";
cout << "*ptr: " << *ptr << "\n";
cout << "a " << a << "\n";



*ptr = 66;



cout << "ptr: " << (unsigned int) ptr << "\n";
cout << "*ptr: " << *ptr << "\n";
cout << "a " << a << "\n";



*ptr++;
*ptr = 67;



cout << "ptr: " << (unsigned int) ptr << "\n";
cout << "*ptr: " << *ptr << "\n";
cout << "a " << a << "\n";

I get the following output:

ptr: 3221202256
*ptr: A
a 65
ptr: 3221202256
*ptr: B
a 66
ptr: 3221202257
*ptr: C
a 17218

I wanted to know, why does the value of a = 17218? Should it not be 67?

Thanks.

Although your programme is a C++ one it's close enough to C
that I will give you an answer here.

You have declared a as int and ptr as pointer to char. This means
that if on your system int occupies a smaller number of bytes than
char, then when you write *ptr = some_value; not all of the bytes
corresponding to a get modified. So a doesn't get the value you want.
If you declare ptr as pointer to int or declare a as char then things
will work as you expect.

Come to think of it even in that case you will encounter problems
because you increment ptr. I'm not sure what you intended to achieve
by writing *ptr++ but I hope you realize that it is the same as writing
*(ptr++) ie it is ptr itself which gets incremented.

.



Relevant Pages