2010-07-12 124 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