在函数内部使用 malloc 形成字符串时出现分段错误 (11)

Mot*_*mot 1 c string malloc c-strings segmentation-fault

我正在尝试使用一个函数来分配空间并用字符填充该空间(或至少其中一部分)以形成字符串。在该函数中,我调用了 malloc,并在同一函数中将字符分配给给定的空间。以下代码给出了我正在做的事情的一般要点:

#define INITIAL 10

int func(char **s);

int
main(int argc, char **argv) {
    char *s;
    int n;

    n = func(&s);
    printf("Done\n");

    return 0;
}

int
func(char **s) {
    int i;

    *s = (char*)malloc(INITIAL*sizeof(char));
    assert(*s);

    for (i=0; i<5; i++) {
        printf("i=%d\n", i);
        *s[i] = 'a'; /*'a' is an arbitrary char for this example */  
    }
    return i;    
}
Run Code Online (Sandbox Code Playgroud)

这段代码的输出是:

i=0
i=1
i=2
Segmentation fault: 11
Run Code Online (Sandbox Code Playgroud)

我让函数返回 int 的原因是因为我最终希望函数返回我形成的字符串的长度。
我完全不确定为什么会出现分段错误;看来我已经分配了足够的空间来容纳下一个字符。它在 i=2 处停止对我来说也很奇怪。如果有人能指出我所犯的错误,我将不胜感激!

Vau*_*ato 5

代替

*s[i] = 'a';
Run Code Online (Sandbox Code Playgroud)

你要

(*s)[i] = 'a';
Run Code Online (Sandbox Code Playgroud)

*s[i]相当于*(s[i]). 也就是说,它将 s 视为字符串数组,并给出索引 i 处字符串的第一个字符。