c - 为什么我不能重新分配这个字符串?

标签 c string pointers struct null-terminated

我有一个这样的结构:

typedef struct TEXT {
    char *text;
    struct TEXT *next;
} TEXT;

在某些函数中我有类似的东西:

TEXT *line = (TEXT *) malloc(sizeof(TEXT));
line->text = NULL; // was "\0" before
char current = getchar();
while (current != '\n') {
    AddChar(&(line->text), current); // Was AddChar(line->text, current);
    current = getchar();
}

AddChar 函数是这样的:

void AddChar(char **text, char c) { //was char *text
    *text = (char *) realloc(*text, strlen(*text)+2); //was text = ...
    char char_array[2] = {c, '\0'); 
    strcat(*text, char_array); //was strcat(text, char_array);
}

不幸的是,程序崩溃了。

据我了解,原来 strlen 无法弄清楚如果 text == NULL,length 应该是 0...

无论如何,使用这个 AddChar 函数,一切正常:

void AddChar(char **text, char c) {
    if (*text == NULL) {
        *text = (char *) malloc(2);
        (*text)[0] = c;
        (*text)[1] = '\0';
    }
    else {
        *text= (char *) realloc(*text, sizeof(*text)+2);
        char char_array[2] = { c , '\0' };
        strcat(*text, char_array);
    }
}

.

.

我也有问题

void AddChar(char *text, char c) {
    text = "something";
}

不更改 line->text,但将 *text 更改为 **text 修复了该问题。

最佳答案

只有 NULL 初始化指针或由 malloc 系列函数返回的指针(malloccallocrealloc) 可以传递给另一个 malloc 系列函数。 line->text 是用字符串文字 "\0" 初始化的,因此 line->text 不能传递给 realloc 函数。
另请注意,您不能修改字符串文字。

关于c - 为什么我不能重新分配这个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570264/

相关文章:

c - 有关 for 循环的更多信息

java - 奇数格式异常

python 从文本文件中获取行+1

c - ((struct name *)0)->member) 在 C 中做什么?

c - 在 C 中创建周期性 Linux 线程的最佳方法是什么

c - 使用 ".h"文件中的结构

c - pthread_posix_mutex - 无法实现功能

c - 低级 IO read() 和 write()

iphone - 将 UInt32(音频帧)拆分为两个 SInt16(左右)?

c++ - 带临时指针的列表遍历 - 声明指针时分配指针引用的节点空间有危险吗?