0

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.

  • You should read about [strcat](https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm) – Rohan Kumar Oct 03 '17 at 06:09
  • Yes, I understand the concatenation part. I need help in passing the string as function argument as well as returning a string from function to main. Thank you. –  Oct 03 '17 at 06:21

3 Answers3

1

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.

Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
0

You might want to see how to properly concatenate strings in C

How do I concatenate const/literal strings in C?

This can help

Lordtien
  • 1
  • 5
  • I understand the concatenation part. I need help in passing the string as function argument as well as returning a string from function to main. Thank you. –  Oct 03 '17 at 06:21
0

You can try this:

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

char * function(char * data);

char * function(char * data)
{
    char * str2 = "there";

    char * str3 = NULL;

    if (data == NULL)
            return NULL;

    int len = strlen (data) + strlen (str2);

    str3 = (char *) malloc (len + 1);

    snprintf (str3, (len+1), "%s%s", data, str2);

    return str3;
}

int main()
{
    char * str1 = "Hello ";

    char * received = function(str1);

    if (received != NULL)
            printf("%s\n", received);
    else
            printf ("received NULL\n");

    if (received != NULL)
        free (received);

    return 0;
}
H.S.
  • 11,654
  • 2
  • 15
  • 32