2013-03-01 125 views
7

我從一本書教自己C,我試圖創造一個縱橫字謎。我需要製作一串字符串,但仍然遇到問題。另外,我不知道很多有關數組...如何在C中創建一個字符串數組?

這是一塊代碼:

char word1 [6] ="fluffy", word2[5]="small",word3[5]="bunny"; 

char words_array[3]; /*This is my array*/ 

char *first_slot = &words_array[0]; /*I've made a pointer to the first slot of words*/ 

words_array[0]=word1; /*(line 20)Trying to put the word 'fluffy' into the fist slot of the array*/ 

但我不斷收到消息:

crossword.c:20:16: warning: assignment makes integer from pointer without a cast [enabled by default] 

不知道是什麼這個問題......我試圖查找如何使一個字符串數組,但沒有運氣

任何幫助將非常感激,

山姆

+0

嘗試研究一下數組http://pw1.netcom.com/~tjensen/ptr/pointers.htm。 – 2013-03-01 16:01:48

+0

順便說一下 - 'char word1 [6] =「蓬鬆」 - 「蓬鬆」實際上是7個字符。在C中,一個字符串以'\ 0'結尾 - 佔用一個額外的字符。 – ArjunShankar 2013-03-01 16:03:34

+2

'const char * arr [] = {「literal」,「string」,「pointer」,「array」};',並注意** const **。 – WhozCraig 2013-03-01 16:03:37

回答

11
words_array[0]=word1; 

word_array[0]char,而word1char *。你的角色無法持有地址。

的字符串數組可能看起來像它:

char array[NUMBER_STRINGS][STRING_MAX_SIZE]; 

如果您更希望指針數組到您的字符串:

char *array[NUMBER_STRINGS]; 

然後:

array[0] = word1; 
array[1] = word2; 
array[2] = word3; 

也許你應該閱讀this

+0

感謝一堆kirilenko! – Wobblester 2013-03-01 16:19:28

7

聲明

char words_array[3]; 

創建三個字符陣列。你似乎想聲明字符指針數組:

char *words_array[3]; 

你雖然有一個更嚴重的問題。聲明

char word1 [6] ="fluffy"; 

創建六個字符數組,但實際上你告訴它有字符。所有字符串都有一個額外的字符,'\0',用於告訴字符串的結尾。

要麼聲明數組是尺寸7:

char word1 [7] ="fluffy"; 

或離開尺寸時,編譯器會看着辦吧本身:

char word1 [] ="fluffy"; 
+0

哦,好的謝謝 – Wobblester 2013-03-01 16:13:54

5

如果你需要的數組字符串。有兩種方法:字符

在這種情況下

1.二維數組,你必須知道你的字符串的大小提前。它看起來像下面:

// This is an array for storing 10 strings, 
// each of length up to 49 characters (excluding the null terminator). 
char arr[10][50]; 

2.字符指針的數組

它看起來像下面:

// In this case you have an array of 10 character pointers 
// and you will have to allocate memory dynamically for each string. 
char *arr[10]; 

// This allocates a memory for 50 characters. 
// You'll need to allocate memory for each element of the array. 
arr[1] = malloc(50 *sizeof(char)); 
4

還可以使用malloc()手動分配內存:

int N = 3; 
char **array = (char**) malloc((N+1)*sizeof(char*)); 
array[0] = "fluffy"; 
array[1] = "small"; 
array[2] = "bunny"; 
array[3] = 0; 

如果你不事先知道(在編碼時)一個數組中有多少個字符串,以及它們會有多長,這是一條路。但是,當它不再使用時,您必須釋放內存(請致電free())。

相關問題