【发布时间】:2010-07-12 02:28:39
【问题描述】:
我已经尝试让它工作好几个小时了,但我似乎无法理解它。
我正在尝试编写一个能够返回字符串数组的函数。
#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字符。如果您声明像char Hello[] = { 'h', 'e', 'l', 'l', 'o', '\0' };这样的字符串,则只需要\0 -
我知道我很讨厌,但请释放你已经 malloc'd 的东西。这是一种很好的做法,如果您在编写代码时始终这样做,您将不会经常忘记。
-
我知道我不需要空终止符,但出于某种原因将其包含在内,感谢您指出这一点。谢谢丹,我通常这样做,但这只是一个测试。谢谢。