jj_94 jj_94 - 1 year ago 177
C Question

String as function argument and returning string from function in C

I would like to do the following pass a string as a function argument and the function will return a string back to main. The brief idea is as below:

String str1 = "Hello ";
String received = function(str1);
printf("%s", str3);


String function (String data){
String str2 = "there";
String str3 = strcat(str3, str1);
String str3 = strcat(str3, str2); //str3 = Hello there
return str3;
}


How do i translate that idea to C? Thank you.

Answer Source

Strings or character arrays are basically a pointer to a memory location, as you might already know. So returning a string from the function is basically returning the pointer to the beginning of the character array, which is stored in the string name itself.

But beware, you should never pass memory address of a local function variable. Accessing such kind of memory might lead to Undefined Behaviour.

#include <stdio.h>
#include <string.h>

#define SIZE 100

char *function(char aStr[]) {
  char aLocalStr[SIZE] = "there! ";
  strcat(aStr, aLocalStr);
  return aStr;
}


int main() {
  char aStr[SIZE] = "Hello ";
  char *pReceived;
  pReceived = function(aStr);
  printf("%s\n", pReceived);
  return 0;
}

I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download