2013-05-05 69 views
0

你能告訴我我在這裏做錯了什麼?我在打印時沒有得到文字printf("%s\n",text[0]);C中的字符串數組與malloc

我創建了char **text;malloc ed所有指針。

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 


char **text; 

int main() 
{ 
    int i; 
    text = malloc(20000); 


    for(i=0; i < 20000; i++) { 
     text[i] = malloc(4); 

     memcpy(text[i], "test",4); 
    } 
    printf("%s\n",text[0]); 
    printf("%s\n",text[1]); 
} 
+3

你的琴絃不以null結尾。 – nickb 2013-05-05 23:19:28

+1

此外,malloc(20000)分配20000 *字節*,然後您試圖填充20000個字符指針(每個需要幾個字節,並相互覆蓋)。 – 2013-05-05 23:27:24

+0

是的,我應該做這個文本= malloc(20000 * sizeof(char *)); – 2013-05-05 23:29:43

回答

2

我相信你正在尋找的東西是這樣的:

int numElements = 20000, i; 
// Allocate an array of char pointers 
text = malloc(numElements * sizeof(char *)); 

for(i = 0; i < numElements; i++) { 
    // 4 for the length of the string "test", plus one additional for \0 (NULL byte) 
    text[i] = malloc((4 + 1) * sizeof(char)); 
    memcpy(text[i], "test\0", 5); 
} 

這裏是一個online demo顯示它的工作,因爲它產生的輸出:

test 
test 
1
for(i=0; i < 20000/sizeof(char*); i++) { 
    text[i] = malloc(5); 
    memcpy(text[i], "test",5); 

} 
+0

或者,當然,將第一個'malloc(20000)'更改爲'malloc(20000 * sizeof(char *))'。 – 2013-05-05 23:29:38

+0

我以爲這可能是...... – BLUEPIXY 2013-05-05 23:35:20