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.

2
  • You should read about strcat Commented Oct 3, 2017 at 6: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. Commented Oct 3, 2017 at 6:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.