c - 如何在 c 中将链表中的所有字符串大写?

标签 c

<分区>

我试图将链表中的所有字符串大写,但我遇到了一个我无法弄清楚的段错误。

这是我目前的代码:

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)

希望对您有所帮助。

关于c - 如何在 c 中将链表中的所有字符串大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684773/

相关文章:

c - 我不断收到此错误 : expected identifier or ‘(’ before ‘<’ token </span>

检查输入是否包含两个整数和一个字符

c - 从C中的十六进制地址中提取MSB和LSB

编译器不执行代码块中的程序

c - 程序没有按预期退出

使用指针输入结构值时 scanf 函数中的混淆

c - 解决iOS中隐式转换丢失整数精度目标警告

编译器#警告: print enum value

更改字符指针数组中的内容

c - IPC 函数 shmat 的标志 SHM_RND 是什么意思?