String作为函数参数并从C函数返回字符串

时间:2017-10-03 06:05:51

标签: c string parameters arguments

我想将以下字符串作为函数参数传递,函数将字符串返回给main。简短的想法如下:

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

我如何将这个想法转化为C?谢谢。

3 个答案:

答案 0 :(得分:1)

字符串或字符数组基本上是指向内存位置的指针,您可能已经知道了。因此,从函数返回一个字符串基本上是将指针返回到字符数组的开头,字符数组存储在字符串名称中。

但要注意,你永远不应该传递本地函数变量的内存地址。访问此类内存可能会导致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;
}

我希望这会有所帮助。

答案 1 :(得分:0)

您可能希望了解如何在C

中正确连接字符串

How do I concatenate const/literal strings in C?

这可以帮助

答案 2 :(得分:0)

你可以试试这个:

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