从函数返回的字符串数组未正常工作 [英] returning array of string from function not working as expected

查看:118
本文介绍了从函数返回的字符串数组未正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个字符串数组传递给一个函数,使该函数内部一些改变它,并把它传递回的main()并打印到看到的变化。它不按预期工作。请告诉我,我要去哪里错了。

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&malloc.h所GT;//别忘了声明此功能
焦炭**的乐趣(的char [] [20]);INT主要(无效)
{
    焦炭STRAR [10] [20] = {{ABC},{高清},{GHI},{},{}}; //确保10加
    焦炭** RET; //无需分配给沤什么,RET只是一个占位符,分配一切都在做的乐趣
    INT I = 0;    RET =乐趣(STRAR);
    对于(I = 0; I&下; 4;我+ +)
        的printf([%S],RET [I]);    的printf(\\ n);
    返回0;
}//不要忘了函数返回的char **,而不是诠释。 (记住CHAR **,不是char *)
焦炭**的乐趣(字符STRAR [] [20])
{
    INT I = 0;
    焦炭** RET;
    RET =的malloc(sizeof的(无效*)); //的sizeof(void *的)就足够了,它只是持有一个地址    对于(I = 0; I&小于5;我+ +)
    {
        RET [I] =的malloc(20 * sizeof的(炭));
        的strcpy(保留[I],STRAR [I]);
    }    的strcpy(保留[3],fromfun);    返回RET;
}


解决方案

您需要确保您分配指针的全阵列的 RET 阵列。

  //不要忘了函数返回的char **,而不是诠释。 (记住CHAR **,不是char *)
焦炭**的乐趣(字符STRAR [] [20])
{
 INT I = 0;
 焦炭** RET;
 RET =的malloc(sizeof的(无效*)* 5); //的sizeof(void *的)就足够了,它只是持有一个地址 对于(I = 0; I&小于5;我+ +)
 {
  RET [I] =的malloc(20 * sizeof的(炭));
  的strcpy(保留[I],STRAR [I]);
 } 的strcpy(保留[3],fromfun); 返回RET;
}

I am trying to pass an array of strings to a function, make some changes to it inside this function, and pass it back to main() and print it to see the changes. It is not working as expected. Please tell me where I'm going wrong.

#include <stdio.h>
#include <string.h>
#include <malloc.h>

//don't forget to declare this function
char** fun(char [][20]);

int main(void)
{
    char strar[10][20] = { {"abc"}, {"def"}, {"ghi"}, {""},{""} }; //make sure 10 is added
    char** ret; //no need to allocate anything for ret, ret is just a placeholder, allocation everything done in fun
    int i = 0;

    ret = fun(strar);
    for(i=0;i<4;i++)
        printf("[%s] ",ret[i]);

    printf("\n");
    return 0;
}

//don't forget function has to return char** and not int. (Remember char**, not char*)
char** fun(char strar[][20])
{
    int i = 0;
    char** ret;
    ret = malloc(sizeof(void*)); //sizeof(void*) is enough, it just has to hold an address 

    for(i=0;i<5;i++)
    {
        ret[i] = malloc(20 * sizeof(char));
        strcpy(ret[i],strar[i]);
    }

    strcpy(ret[3],"fromfun");

    return ret;
}

解决方案

You need to make sure that you allocate the full array of pointers for ret array.

//don't forget function has to return char** and not int. (Remember char**, not char*)
char** fun(char strar[][20])
{
 int i = 0;
 char** ret;
 ret = malloc(sizeof(void*) * 5); //sizeof(void*) is enough, it just has to hold an address 

 for(i=0;i<5;i++)
 {
  ret[i] = malloc(20 * sizeof(char));
  strcpy(ret[i],strar[i]);
 }

 strcpy(ret[3],"fromfun");

 return ret;
}

这篇关于从函数返回的字符串数组未正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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