我已經嘗試了一切,我的代碼看起來對我來說非常好(顯然不是如果它不工作)。如何在不知道字符串和字符大小的情況下動態創建C中的字符串數組?
我想從某些文本中讀取由逗號分隔的單詞列表,並且每個單詞都將是一個字符串數組的元素。我不知道會有多少元素或多久。
for循環是宏偉的,因爲我計算了之前有多少個字符。主要的問題是分配內存,有時我得到「段錯誤:11」當我運行它(因爲它編譯盛大),有時當我讀到的項目也得到類似:
P 25一路平安(空)heyya
時候就應該給我的東西,如:
HOLA一路平安再見heyya
我想我訪問內存我不應該。總之,這裏的代碼:
// We allocate memory for one string
variables = (char**)calloc(1, sizeof(char*));
variables[0] = (char*)calloc(100, sizeof(char));
if (variables == NULL) {
return NULL;
}
// Now we start looking for the variables
for (int i = comma_pos+1; i < *(second_pos + pos); i++) {
deleteSpaces(string, &i);
// If the character is not a comma, we copy the character
if (*(string + i) != ',') {
*(variables[stringnum] + j) = *(string + i);
j++;
} else {
// If the character is a comma, we have to allocate more memory for a new string
*(variables[stringnum] + j) = '\0';
stringnum++;
j = 0;
char **temp = variables;
// We allocate more memory for a second array
variables = realloc(variables, sizeof(char*) * stringnum);
variables[stringnum] = (char*)calloc(100, sizeof(char));
// If we cannot allocate more memory then get out
if (variables == NULL) {
return temp;
}
} // end else
} // end for
*(variables[stringnum] + j) = '\0';
您的變量的定義不瑣碎細節,爲簡潔起見被省略,*他們是非常重要*。 **給他們看**。 –
我知道它可以做到,但是需要分配一個指針數組,然後深入,然後對於該數組中的每個指針,您需要對另一個alloc進行重新分配,然而對於每一行重複一次,所以如果您有8個深刻你做了9次分配...不管多寬。 –
把它當作一維數組/指針來分配所有字符串的空間,然後鏈接列表或以某種方式跳過它們,這樣更容易。 –