为什么我无法重新分配该字符串?

Jec*_*cke 2 c string struct pointers null-terminated

我有一个这样的结构:

typedef struct TEXT {
    char *text;
    struct TEXT *next;
} TEXT;
Run Code Online (Sandbox Code Playgroud)

在某些功能中我有类似的东西:

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();
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,程序崩溃了。

据我了解,事实证明 strlen 无法弄清楚如果 text == NULL,则长度应该为 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我也遇到了问题

void AddChar(char *text, char c) {
    text = "something";
}
Run Code Online (Sandbox Code Playgroud)

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

hac*_*cks 5

只有已初始化的指针或族函数(、和)NULL返回的指针才能传递给另一个族函数。使用字符串文字初始化,因此无法传递给函数。 另请注意,您无法修改字符串文字。mallocmalloccallocreallocmallocline->text"\0"line->textrealloc