2010-07-12 161 views
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; 
} 

我可能得到夹杂了指针的地方,因为我得到以下输出:

你好
分段错误

+2

你不需要'\ 0'在字符串的末尾。当你使用双引号时,编译器为你添加'\ 0'字符。你只需要'\ 0',如果你声明你的字符串是'char'[] = {'h','e','l','l','o','\ 0'};' – 2010-07-12 02:34:47

+1

I知道我是一个讨厌的人,但请释放你有malloc'd。这是一个很好的做法,如果你在编写代码时总是这么做,那么你就会经常忘记。 – Daniel 2010-07-12 02:39:20

+0

我知道我不需要空终止符,但包括它出于某种原因,谢谢指出。谢谢丹,我通常这样做,但这只是一个测试。谢谢。 – Kewley 2010-07-12 11:45:09

回答

10

是的,你有你的指针间接寻址混合起来,成员Data array的设置应该像这样:

(*Data)[0] = Hello; 
(*Data)[1] = Goodbye; 

在函数中,Data要点来一个数组,它不是一个数组本身。

另一个注意事项:您不需要在字符串文字中加上明确的\0字符,它们会自动以空字符结尾。

+0

我最初尝试过,并不明白为什么它不起作用,但我没有使用括号。非常感谢!! :) – Kewley 2010-07-12 11:43:50