2015-12-06 26 views
-3

我想創建一個字符串數組,其中我沒有每個字符串的修復長度。我該怎麼做? 這是我的代碼:如何在C中創建一個動態的字符串數組?

char **a; 
int n, m; 
scanf_s("%d %d", &n, &m); 
a = (char**)malloc(n*sizeof(char*)); 
for (int i = 0; i < n; i++) 
    a[i] = (char*)malloc(m*sizeof(char)); 

for (int i = 0; i < n; i++) 
    for (int j = 0; j < m;j++) 
    scanf_s(" %c", &a[i][j]) 

我必須輸入字的數組,我不知道他們的lenght。在這段代碼中,我只能輸入一定長度的單詞,我想改變它。

+0

'malloc' a'char **',然後'malloc'每個字符串所需的空間,將指針存儲在各自的索引中由第一個'malloc'創建的數組。 –

+0

我已經這樣做了,但是我想輸入不同的詞。 –

+2

到目前爲止你做了什麼,你卡在哪裏?顯示你的代碼。 – Olaf

回答

1

我想製作一個字符串數組,其中我沒有修復長度爲 的每個字符串。我該怎麼做?

數組本身的長度是否固定?如果是:

char *charPtr[5]; // Can refer to 5 different strings of different length each 
for(int i = 0; i<5; i++) 
{ 
charPtr[i] = malloc(SOME_DYNAMICLEN); // can specify different length for each string 
strcpy(charPtr[i], "test"); // initialize i-th string 
} 

請不要忘記free以後的每個字符串。

1

什麼@Daniel說一個例子是:

int NumStrings = 100; 
char **strings = (char**) malloc(sizeof(char*) * NumStrings); 
for(int i = 0; i < NumStrings; i++) 
{ 
    /* 
     Just an example of how every string may have different memory allocated. 
     Note that sizeof(char) is normally 1 byte, but it's better to let it there */ 
    strings[i] = (char*) malloc(sizeof(char) * i * 10); 
} 

如果您不需要malloc之初每個字符串,以後可以做到這一點。如果您需要更改分配的字符串數量(執行reallocstrings),則可能稍微複雜一點。

+0

'char strings = malloc(...)' - >'char **' – szczurcio

+0

這只是一個例子。也許小一點對你更好? (編輯答案) – emi

+0

你也可以做明確的類型轉換(再次編輯...) – emi

-2

分配一個字符串數組char ** mystrs = malloc(numstrings * sizeof(char *))。現在mystrs是一個指針數組。現在,您只需要爲每個要添加的字符串使用malloc。

mystrs [0] = malloc(numchars +1 * sizeof(char))。 //爲空字符添加額外字符

然後您可以使用strcpy複製字符串數據。 strcpy(mystrs [0],「my string」)

相關問題