我试图将链表中的所有字符串大写,但我遇到了一个我无法弄清楚的段错误。
这是我目前的代码:
wordnode_t *upperAll(wordnode_t * indexWords){
wordnode_t *upperIndexWords = NULL;
wordnode_t *ptr = indexWords;
while(ptr){
char *word = ptr -> w;
int i = 0;
for (i=0; word[i]; i++){
word[i] = toupper((unsigned char)word[i]);
}
upperIndexWords = add_end(indexWords, new_word(word, 0));
ptr = ptr -> next;
}
return upperIndexWords;
}
其中wordnode_t是链表中的节点,w是节点中的字符串。
当您尝试读取或写入尚未分配给您的程序或不可写的地址时,您会遇到段错误。很明显,您的程序正在尝试读取未分配或不可访问的内存。我相信您的 wordnode_t
看起来像这样:
struct wordnode_t{
char *w;
wordnode_t *next;
}
在这种情况下,您会遇到段错误,因为此 word[i] = ...
试图直接修改指向字符串文字的指针 char *word = ptr->w
不允许或根本无法修改。
我的解决方案是复制 ptr->w
而不是为其分配另一个名称并尝试修改它。差不多是这样
char *word = strdup(ptr->w);
int i = 0;
for (i; word[i]; i++) {
if (islower(word[i]))
word[i] = toupper((unsigned char) word[i]);
i++;
}
或者如果你像我一样不太喜欢使用 using 函数,
char *str = strdup(word);
int i = 0;
while (str[i]) {
if (str[i] >= 97 && str[i] <= 122)
str[i] -= 32;
i++;
}
如果您正在寻找标准方式,那么请避免 strdup
并更加大胆。使用 malloc
#include <string.h>
...
char *word = (char*)malloc(strlen(ptr->w) * sizeof(char));;
strcpy(word, ptr->w);
int i = 0;
for (i; word[i]; i++) {
if (word[i] >= 97 && word[i] <= 122)
word[i] -= 32;
}
完成后不要忘记free(word)
。
希望对您有所帮助。