5
我一直试图让这个工作好几个小时,但我似乎无法得到我的头。返回字符串阵列
我想写一个能够返回字符串数组的函数。
#include <stdio.h>
#include <stdlib.h>
/**
* This is just a test, error checking ommited
*/
int FillArray(char *** Data);
int main()
{
char ** Data; //will hold the array
//build array
FillArray(&Data);
//output to test if it worked
printf("%s\n", Data[0]);
printf("%s\n", Data[1]);
return EXIT_SUCCESS;
}
int FillArray(char *** Data)
{
//allocate enough for 2 indices
*Data = malloc(sizeof(char*) * 2);
//strings that will be stored
char * Hello = "hello\0";
char * Goodbye = "goodbye\0";
//fill the array
Data[0] = &Hello;
Data[1] = &Goodbye;
return EXIT_SUCCESS;
}
我可能得到夹杂了指针的地方,因为我得到以下输出:
你好
分段错误
你不需要'\ 0'在字符串的末尾。当你使用双引号时,编译器为你添加'\ 0'字符。你只需要'\ 0',如果你声明你的字符串是'char'[] = {'h','e','l','l','o','\ 0'};' – 2010-07-12 02:34:47
I知道我是一个讨厌的人,但请释放你有malloc'd。这是一个很好的做法,如果你在编写代码时总是这么做,那么你就会经常忘记。 – Daniel 2010-07-12 02:39:20
我知道我不需要空终止符,但包括它出于某种原因,谢谢指出。谢谢丹,我通常这样做,但这只是一个测试。谢谢。 – Kewley 2010-07-12 11:45:09