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