|
|
View previous topic :: View next topic |
Author |
Message |
ch_dupre
Joined: 22 Aug 2006 Posts: 18
|
assigning a value to a pointer |
Posted: Tue Nov 07, 2006 11:30 am |
|
|
hello forum,
I'm having some trouble with pointers. First I wanted to have a function that return a pointer but the result was weird. I tried different method, but the results are still incorrect.
Here is a sample code
****************************************************************
int16 data;
int16* returnPtr(void)
{
fprintf(COM2, "address of data: %LX\n", &data);
return &data;
}
void returnPtr2(int16* PTR)
{
PTR = &data;
fprintf(COM2, "address of PTR: %LX\n", PTR);
}
void main()
{
int16* ptr;
int16* localPtr;
ptr = returnPtr();
fprintf(COM2, "address of ptr: %LX\n", ptr);
returnPtr2(ptr);
fprintf(COM2, "address of ptr: %LX\n", ptr);
fprintf(COM2, "address of localPtr: %LX\n", localPtr);
localPtr += 0xFF;
fprintf(COM2, "address of localPtr: %LX\n", localPtr);
localPtr = &data;
fprintf(COM2, "address of data: %LX\n", &data);
fprintf(COM2, "address of localPtr: %LX\n", localPtr);
}
**************************************************************
Here is the output I get:
address of data: 0605
address of ptr: 0005 <<== I would expect 0605 back
address of PTR: 0005 <<== same thing. I expect 0605 here
address of ptr: 0005
address of localPtr: 0005
address of localPtr: 0203 <<==this one makes sense: FF + 5 = 0x203
address of data: 0605
address of localPtr: 0005 <<== again, I expect 0x0605.
Am I doing something wrong? Or is there a limitation in the compiler.
I've tried using compile V3.249 and V4.013
Thanks,
Christophe |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue Nov 07, 2006 1:52 pm |
|
|
The true address for 'data' is 0006. I compiled your program for an
18F452, and then looked at the Symbol Table. It shows that 0006 is the
address.
I think printf is very buggy for displaying the address of a variable.
To fix the problem, I had to cast the '&data' value to an int16, as shown
in bold below. I tested this with PCH vs. 3.249.
Quote: |
fprintf(COM2, "address of data: %LX\n", (int16)&data);
fprintf(COM2, "address of localPtr: %LX\n", localPtr); |
Then it displays:
Quote: | address of data: 0006
address of localPtr: 0006 |
I just worked on the last two lines of your program. But it's likely
that you can fix the rest of it in a similar way. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|