简体   繁体   中英

How to return a buffer address in C

I'm trying to create a function that creates an string in RAM of a 16 bit microcontroller. The function prototype is like this

char CID_Str[12] GetContactID(char Qual,long Event,char Partition,char Zone);

The function should return a little string created with the input parameters.

I never do it a function like this before. I don't need help with the code inside the function. I need to know how should I declare the returning parameter (Buffer) because the CCS compiler doesn't like that prototype.

Arrays can be returned as a pointer to the array element type. The returned pointer would be the address of the first element in the array (or memory region). In your case:

char *GetContactID(char Qual,long Event,char Partition,char Zone);

And to your comment:

I just created a buffer inside the variable like this char ContactID[12]; then at the end of the function i have a return ContactID;

Be sure not to return stack addresses (eg local variable address). Such an address is only valid within the scope of the function and becomes an invalid (dangling) pointer if returned to the caller. Main options are:

  1. Allocate dynamic memory in the function and return that as the function return value or in an output parameter. Caller is responsible for freeing the memory.
  2. Caller passes in a memory address.
  3. Use static memory.

The first two are the usual cases.

Update: I missed the fact that you are running on a microcontroller. In that case, static memory may be more appropriate as such systems tend not to want the overhead and complexity of dynamic allocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM