|
|
View previous topic :: View next topic |
Author |
Message |
Guest
|
Returning pointer to int32 |
Posted: Sat Jan 31, 2009 10:51 am |
|
|
What is wrong here?
It's only a small test program to show my problem.
I want to return a pointer to a int32.
I have another function returning a string it work.
Cant compile.
Code: | int32 serialno;
int8 *serial_no(){
return (serialno);
}
printf("%Lu",serial_no); |
working:
Code: | char serialstr[10];
int8 *serial_str(){
return (serialstr);
}
printf("%s",serialstr); |
|
|
|
Guest
|
|
Posted: Sat Jan 31, 2009 10:54 am |
|
|
Sorry right type.
printf("%Lu",serial_no());
printf("%s",serial_str()); |
|
|
Ttelmah Guest
|
|
Posted: Sat Jan 31, 2009 2:04 pm |
|
|
Code: |
int32 serialno;
//first the function is returning a pointer to an int32, not an int8....
int32 *serial_no(){
//second, the pointer, is the address of the variable, not the variable
//itself.
return (&serialno);
}
//Third, the print, needs to reference the contents of the pointer
printf("%Lu",*serial_no());
|
On your 'does compile' version, you are getting away with using the array name, since in C, _when dealing with an array_, the name of the array is a shorthand, for it's address.
Your print then accesses the array, not the function though.....
Best Wishes |
|
|
Guest
|
|
Posted: Sun Feb 01, 2009 4:15 am |
|
|
Thanks
But something I dont understand is what type to select in the pointer int, int16, int32...
Ex.
Why not working with int8? When the string function is working.
Code: | int32 serialno;
[b]int8[/b] *serial_no(){
return (&serialno);
}
printf("%Lu",*serial_no()); |
This is working, but is it right.
I don't use "&" because the str[] is a pointer right?
Code: | char str[11];
[b]int8 [/b]*serial_str(){
return (str);
}
printf(serial_str()); //must I use "*"? It work without.
|
Confused:-( |
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Sun Feb 01, 2009 10:06 am |
|
|
The compiler tells why: It is expecting an int32 expression, but *serial_no() is int8. You didn't tell, why do you want use a wrong pointer type?
If meaningful at all, you can do with a type cast:
Code: | printf("%Lu",*(int32*)serial_no()); |
|
|
|
Ttelmah Guest
|
|
Posted: Sun Feb 01, 2009 12:33 pm |
|
|
Key to understand, is that a 'char', _is_ an int8 (in CCS). Int, int8, char, and byte, are all exactly the same type. Hence the 'int8' pointer, works as expected.
The name of an array, is a 'C shortcut', to the pointer to it, so in your example, 'str', is equivalent to '&str[0]'. However this only works with arrays.
Best Wishes |
|
|
|
|
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
|