C语言 从函数返回 char[]/string

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14416759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:05:26  来源:igfitidea点击:

Return char[]/string from a function

carraysstringcharreturn

提问by user1993177

Im fairly new to coding in C and currently im trying to create a function that returns a c string/char array and assigning to a variable.

我对 C 编码相当陌生,目前我正在尝试创建一个函数,该函数返回 ac 字符串/字符数组并分配给一个变量。

So far, ive observed that returning a char * is the most common solution. So i tried:

到目前为止,我观察到返回一个 char * 是最常见的解决方案。所以我试过:

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char str[3];
    str[0] = char1;
    str[1] = char2;
    str[2] = '
char * createStr() {

    char char1= 'm';
    char char2= 'y';

    char *str = malloc(3);
    str[0] = char1;
    str[1] = char2;
    str[2] = '
char *returned_str = createStr();
'; return str; }
'; char* cp = str; return cp; }

My question is how do I use this returned char*and assign the char array it points to, to a char[] variable?

我的问题是如何使用返回的值char*并将其指向的 char 数组分配给 char[] 变量?

Ive tried (all led to noob-drowning errors):

我试过(都导致了菜鸟淹死的错误):

  1. char* charP = createStr();
  2. char myStr[3] = &createStr();
  3. char* charP = *createStr();
  1. char* charP = createStr();
  2. char myStr[3] = &createStr();
  3. char* charP = *createStr();

回答by Rubens

Notice you're not dynamically allocating the variable, which pretty much means the data inside str, in your function, will be lost by the end of the function.

请注意,您没有动态分配变量,这几乎意味着str函数中的内部数据将在函数结束时丢失。

You should have:

你应该有:

char *returned_str = createStr();

//doSomething
...

free(returned_str);

Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:

然后,当您调用该函数时,将接收数据的变量的类型必须与函数返回的类型相匹配。所以,你应该有:

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char *str = malloc(3 * sizeof(char));
    if(str == NULL) return NULL;
    str[0] = char1;
    str[1] = char2;
    str[2] = '
char* charP = createStr();
'; return str; }

It worths mentioning that the returned value must be freed to prevent memory leaks.

值得一提的是,必须释放返回值以防止内存泄漏。

#include <string.h>
    char* createStr(){
    static char str[20] = "my";
    return str;
}
int main(){
    char a[20];
    strcpy(a,createStr()); //this will copy the returned value of createStr() into a[]
    printf("%s",a);
    return 0;
}

回答by Aniket Inge

If you want to return a char*from a function, make sure you malloc()it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.

如果您想char*从函数中返回 a ,请确保您使用malloc()它。堆栈初始化的字符数组在返回时没有意义,因为从该函数返回后访问它们是未定义的行为。

change it to

将其更改为

char * createStr() 
{
    char char1= 'm';
    char char2= 'y';

    static char str[3];  
    str[0] = char1;
    str[1] = char2;
    str[2] = '##代码##';

    return str;
}

回答by Paul

##代码##

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

如果您的功能正确,那将是正确的。不幸的是,您正在返回一个指向函数中局部变量的指针,这意味着一旦函数返回,它就是一个指向未定义数据的指针。您需要对函数中的字符串使用像 malloc 这样的堆分配,以便您返回的指针具有任何意义。然后你需要记住稍后释放它。

回答by Adnan

Including "string.h" makes things easier. An easier way to tackle your problem is:

包括“string.h”使事情变得更容易。解决您的问题的更简单方法是:

##代码##

回答by A.salehy

you can use a static array in your method, to avoid lose of your array when your function ends :

您可以在方法中使用静态数组,以避免在函数结束时丢失数组:

##代码##

Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)

编辑:正如 Toby Speight 所提到的,这种方法不是线程安全的,而且调用该函数会导致某些应用程序中不需要的数据覆盖。因此,一旦从函数返回,就必须将数据保存在缓冲区中。(但是因为它不是线程安全的方法,并发调用在某些情况下仍然会产生问题,为了防止这种情况你必须使用锁。进入函数时捕获它并在复制完成后释放它,我不喜欢使用它方法,因为它凌乱且容易出错。)