<分区>
我正在尝试将一个字符串数组传递给一个函数,在此函数中对其进行一些更改,然后将其传递回 main()
并打印它以查看更改。它没有按预期工作。请告诉我哪里出错了。
#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;
}