當使用 qsort() 嘗試組織指標陣列時,我總是在雙指標的第一個元素上得到垃圾。我懷疑它指向了錯誤的記憶體地址,我只是不明白。
我對 C 非常陌生(大約 3-4 周),如果有人可以幫助我理解為什么我得到不好的價值并建議我如何解決這個問題,我將不勝感激。
代碼:
char *token;
char **string_array = calloc(wordcount, sizeof(char));
if (!string_array){
fprintf(stderr, "couldn't make double pointer\n");
}
size_t str_array = 0;
token = strtok(w2->data, "\n\t ");
printf("token %ld: %s\n",str_array, token);
size_t tok_len = strlen(token);
string_array[str_array] = calloc(tok_len,sizeof(char));
if (!string_array[str_array]){
fprintf(stderr, "could not find any of your words\n");
return;
}
if (!strncpy(string_array[str_array ], token, tok_len)){
return;
}
for (int x = 1; x<wordcount; x ){
token = strtok(NULL, "\n\t ");
tok_len = strlen(token);
string_array[str_array] = calloc(tok_len,sizeof(char));
if (!string_array[str_array]){
fprintf(stderr, "failed somewhere with other tokens\n");
return;
}
printf("token %ld: %s\n",str_array, token);
if (!strncpy(string_array[str_array ], token, tok_len)){
puts("could not find one of your words\n");
return;
}
}
qsort(string_array, str_array, sizeof(*string_array), lexsort);
for (int x = 0; x<wordcount; x ){
printf("%s\n",string_array[x]);
}
return;
}
程式的輸出如下所示:
**//shows me what flags the user has set**
a selected
this is the most recent character: a
**//debugging though print statements**
The struct was made
gathering words
Allocated space
** //lines of words read in from file passed on the command line**
token 0: is
token 1: a
token 2: file
token 3: of
token 4: 123:LK
token 5: words
token 6: 123456789
**//output after the array has been sorted**
123456789
123:LK
**//this blank spot is the first element of the array and sometimes it's random garbage from memory (depending on the word)**
a
file
of
words
已經嘗試過:
我想如果我擴展雙指標陣列 1 (calloc((wordcount 1), sizeof(char))并開始在陣列的第一個索引處添加元素而不是第零個索引(str_array = 1;)它可能幫助,但它只是段錯誤(自然......)
uj5u.com熱心網友回復:
首先,雙指標是指向指標的指標,因此在 中calloc您必須使用char *而不是,char并且您應該記住也初始化內部指標,您實際上在這里做了string_array[str_array] = calloc(tok_len,sizeof(char));。
其次,C 中的字串是空終止的,這意味著 C 存盤Hello,H e l l o NULL所以當你有strlen等于 5 時,你需要一個包含 6 個元素的陣列來存盤它。
string_array[str_array] = calloc(tok_len,sizeof(char) 1);
您的代碼中的以下行是正確的:
if (!strncpy(string_array[str_array ], token, tok_len)){
return;
}
但最好把它寫成更具可讀性:
if (!strncpy(string_array[str_array], token, tok_len)){
return;
}
str_array ;
關于qsort,我認為它是正確的,并且會按預期作業。同樣, usingsizeof(char *)比sizeof(*string_array).
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532299.html
標籤:C指针双指针
