警告:“s”在此函数中使用未初始化 [-Wuninitialized]

warning: ‘s’ is used uninitialized in this function [-Wuninitialized]

基本上在最基本的层面上我无法理解为什么我不能这样做:

#include <stdio.h>
#include <stdlib.h>

void mal(char *str){
    str = malloc(sizeof(char));
}



int main(void)
{
    char *s;
    mal(s);
    free(s);
    return 0;
}  

s 按值传递给函数 mal。在 mal 内部,局部参数 str 被赋值更改,但 main 中的 s 保持未初始化状态。在 C 中,您应该将指向 s 的指针传递给 mal 以解决此问题:

#include <stdio.h>
#include <stdlib.h>

void mal(char **str){ // pointer to pointer
    *str = malloc(sizeof(char)); // referenced variable behind str changed
}



int main(void)
{
    char *s;
    mal(&s); // pointer to s passed
    free(s);
    return 0;
}