pointer problem in c.
Hi,
I never understod the notation in c and pointers. This is the problem that I do not understand how to save the return of the function. Shall I make a ptr for it? Is ret saved in ret[32](if yes is it safe)? Can I store the bytes in ret[32] from the returned pointer direcly? Whats the best to do? I want to understand this because I always get bugs with pointers in c and its a wast of time. I have: file one: ... char ret[32]; ... ???? = getMechStatus(ret); file two: char * getMechStatus(char ret[]) { ... ... return ret; } |
ok just
getMechStatus(ret); works fine. Are there any drawbacks? |
Quote:
Code:
file one: Code:
void getMechStatus(char *ret) Code:
printf("%d\n",sizeof(ret)); Also, it's up to you to make sure that getMechStatus() stays within the 32 bytes of the array. Obviously, you can't use sizeof() within getMechStatus() to help you. getMechStatus() has no inherent way to test the size of the array. Also, please keep in mind that the global ret and the parameter ret within getMechStatus() are two separate creatures; the following code would act identically, and most people would probably code two separate names to remind them of this. Code:
file one: |
I would also introduce another parameter:
Code:
void getMechStatus(char ret[], int retLen) |
Quote:
Quote:
Quote:
Quote:
Quote:
So mainly it is a question of whether you understand what the code you have actually does. Quote:
Quote:
Quote:
Mainly for readability, the one it takes is a char[] which won't affect the generated code but may make the interface more understandable for someone writing a call to it. Quote:
|
Thanks a lot now its more clear.
I did not realize that with getMechStatus(ret) that I just send the pointer. And I did not know the thing with sizeof and the solution void getMechStatus(char ret[], int retLen). Since I att most use 32 bytes the lengt is not a problem. Its for a coinmech via serialport. But maybe I chould check the length if I want to reuse this code in another project in the future. Just to make it safe. Thanks again. I have the problem that I sit at home working and I have no one to ask. I do not even know any one personally that programs in c or know c. |
All times are GMT -5. The time now is 02:29 AM. |