从函数返回 char[]/string [英] Return char[]/string from a function

查看:41
本文介绍了从函数返回 char[]/string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

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

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

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

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

推荐答案

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

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.

你应该:

char * createStr() {

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

    char *str = malloc(3);
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return 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 *returned_str = createStr();

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

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

char *returned_str = createStr();

//doSomething
...

free(returned_str);

这篇关于从函数返回 char[]/string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆