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

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

问题描述

林相当新在C编码,目前即时通讯试图建立一个返回C字符串/字符数组的函数,赋值给一个变量。

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

 的char * createStr(){
    焦炭CHAR1 ='M';
    焦炭CHAR2 ='Y';
    炭海峡[3];
    海峡[0] = char1的;
    海峡[1] = CHAR2;
    海峡[2] ='\\ 0';
    字符* CP = str中;
    返回CP;
}

我的问题是我如何使用这个返回的char *,并指定字符数组指向,为char []变量?

我用尽(所有导致小白溺水错误):


  1. 的char * CHARP = createStr();

  2. 字符myStr的[3] =&放大器; createStr();

  3. 的char * CHARP = * createStr();


解决方案

注意你不是动态分配的变量,pretty多指在 STR ,在功能,将由函数的末尾丢失。

您应该有:

 的char * createStr(){    焦炭CHAR1 ='M';
    焦炭CHAR2 ='Y';    字符*海峡=(字符*)malloc的(的sizeof(字符)* 3);
    海峡[0] = char1的;
    海峡[1] = CHAR2;
    海峡[2] ='\\ 0';    返回海峡;}

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

 的char * returned_str = createStr();

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.

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

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();

解决方案

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.

You should have:

char * createStr() {

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

    char *str = (char *) malloc(sizeof(char) * 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();

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

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