2015-01-11 44 views
1

我是一個小菜,所以不要難過。如何在C中動態分配一個字符串數組?

而不是像這樣;

char string[NUM OF STRINGS][NUM OF LETTERS]; 

是否可以動態分配多少字符串會使用malloc數組中就好像當你動態地字符指針分配內存?這樣的事情:

int lines; 
scanf("%d", &lines); 
char *string[NUM OF LETTERS] 
string = malloc(sizeof(char) * lines); 

我試過了,但它不起作用;必須有一些我做錯了。 我想到了其他的解決辦法是:

int lines; 
scanf("%d", &lines); 
char string[lines][NUM OF LETTERS]; 

,但我想知道這是否使用malloc是可能的。

+0

這可以幫助嗎? http://stackoverflow.com/a/25755572/1392132 – 5gon12eder

回答

3

您還可以使用malloc每個字,這樣

char **array; 
int lines; 
int i; 

while (scanf("%d", &lines) != 1); 

array = malloc(lines * sizeof(char *)); 
if (array != NULL) 
{ 
    for (i = 0 ; i < lines ; ++i) 
    { 
     int numberOfLetters; 

     while (scanf("%d", &numberOfLetters) != 1); 
     array[i] = malloc(numberOfLetters); 
    } 
}  

其中numberOfStringslengthOfStrings[i]是代表你想數組包含字符串的數量,i個字符串的長度整數該陣列分別。

+0

值得注意的是,這不等同於'char string [NUM OF STRINGS] [NUM OF LETTERS];'。這個版本不是連續的。相反,OP可能(或可能不是,在這種情況下)想要做一個numberOfStrings * numberOfLetters的malloc。 – tux3

+0

這很好。謝謝 –

+0

爲什麼不需要類型轉換? malloc返回void *,但在這種情況下沒有類型轉換 – Mayank

0
int lines; 
scanf("%d", &lines); 
char (*string)[NUM OF LETTERS] 
string = malloc(sizeof(*string) * lines); 
+0

你應該解釋爲什麼這會起作用,而'* string [NUM OF LETTERS]'不適用。 –

+0

使用指針數中的字符數很有趣。 – BLUEPIXY

+0

所以當我使用這個'char * string [NUM OF LETTERS]'NUM OF LETTERS實際上是指針的數量?我很困惑。 @BLUEPIXY –

2

你有兩種方法來實現它。

首先比較複雜,因爲它需要爲指向字符串的指針數組分配內存,併爲每個字符串分配內存。

可以分配的內存整個陣列:

char (*array)[NUM_OF_LETTERS]; // Pointer to char's array with size NUM_OF_LETTERS 
scanf("%d", &lines); 
array = malloc(lines * NUM_OF_LETTERS); 
. . . 
array[0] = "First string\n"; 
array[1] = "Second string\n"; 
// And so on; 

第二種方法的一個缺點是,NUM_OF_LETTERS字節被分配爲每個字符串。所以如果你有很多短字符串,第一種方法對你會更好。

+0

我現在明白了。非常感謝你。 –

1

如果你想連續的內存分配:

char **string = malloc(nlines * sizeof(char *)); 
string[0] = malloc(nlines * nletters); 
for(i = 1; i < nlines; i++) 
    string[i] = string[0] + i * nletters; 

對於更詳細的解釋:讀FAQ list · Question 6.16

0
char **ptop; 
int iStud; 
int i; 
printf("Enter No. of Students: "); 
scanf("%d",&iStud); 

ptop=(char **) malloc(sizeof(char)*iStud); 
flushall(); 


for(i=0;i<iStud;i++) 
{ 
     ptop[i]=(char *) malloc(sizeof(char)*50); 
     gets(ptop[i]); 
} 


for(i=0;i<iStud;i++) 
{ 
    puts(ptop[i]); 
} 
free(ptop); 
相關問題