简体   繁体   中英

How to return 2 char pointers from function?

I need to create a function that takes in a pointer to part of a string and returns a pointer to the beginning of the first word in the string and a pointer to the string after the word .

The characters of a word are defined as upper case and lower case letters, and characters like '-'.

Mainly, I'm not sure how we would return two pointers from a function.

I also don't have the best grasp on pointers so I'm looking for any tips on what a function like this might look like.

first approach

One way to do it is by returning the result in the function arguments (by Dereferencing the callee pointers, which he need to provide in the calling statement)

void process_my_string(const char* userString, char** ptr_firstWord, char** ptr_stringAfter);

how we call it?

char* pfirst = NULL;
char* plast = NULL;
const char* str="hello c pointers";

process_my_string(str, &pfirst, &plast);

second approach

one of the pointers will be returned in the return value and the other in the function passed argument (like the first approach):

char* process_my_string(const char* userString, char** ptr_stringAfter);

how we call it?

char* pfirst = NULL;
char* plast = NULL;
const char* str="hello c pointers";

pfirst = process_my_string(str, &plast);

third approach

return the pointers (both of them) in a structure or an array of pointers. I have chossed to return in my s_return structure below:

typedef struct{
   char* p_first;
   char* p_after;
} s_return;

now the function becomes:

s_return process_my_string(const char* userString);

how we call it?

const char* str="hello c pointers";
s_return my_return = process_my_string(str);

/*access the pointers*/
printf("%s\n", my_return.p_first);
printf("%s\n", my_return.p_last);

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