I can see this has been asked countless times but I couldn't quite relate the answers I found my individual situation. I'm still getting the hang of C and haven't quite got my head around pointers yet. A basic version of the code I'm having issue with is below:
int function(unsigned long *timestamp)
{
timestamp = GetTick();
}
Where the GetTick()
function returns a value of type uint32_t
.
My problem then is that I get a compiler warning that the assignment makes a pointer from an integer without a cast. I understand that pointers and variables are different but I don't fully understand what the meaning of the warning is nor the right way to make the assignment? Any suggestions?
Edit: Might be worth mentioning that I didn't write this code myself, I'm simply trying to port it to use a new set of drivers that should allow it to do the same thing, in theory.
Update:
A cleaner version of the above code:
int function(unsigned long *timestamp)
{
if (timestamp)
timestamp = GetTick();
return 0;
}
答案 0 :(得分:4)
My problem then is that I get a compiler warning that the assignment makes a pointer to an integer
No, the warning is saying the opposite: you're making an integer into a pointer. That's because GetTick
returns an integer but you're assigning the result to timestamp
, which is a pointer. You probably meant:
*timestamp = GetTick();
答案 1 :(得分:4)
You need to use:
*timestamp = GetTick();
as you have passed pointer and you need to set the value at the memory address pointed to by the pointer.
答案 2 :(得分:2)
timestamp
is a pointer, GetTick()
returns a value.
You should do
int function(unsigned long *timestamp)
{
*timestamp = GetTick();
}
答案 3 :(得分:1)
a pointer is just an address unsigned long *timestamp= NULL
. To get the underlying value stored at that address you must de-reference the pointer *timestamp
. since you are passing in a pointer to the function if you want to assign a value you must use, in this case, *timestamp = GetTick();
In addition, if(timestamp)
will be checking the pointer address. if you want it to check if there is an existing value within the pointer you again need to de-reference, if(*timestamp)