char *指针作为形参传递

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

void dup_test(char *c);

int main() 
{
    char* c;
    
    printf("In main, the address of c is %p\n", &c);
    dup_test(c);
    printf("In main: %s\n", c);  

    return 0;
}

void dup_test(char *c) 
{
    char* msg = "hello world\n";

    printf("In dup_test, the address of c is %p\n", &c);
    printf("origin msg: %s\n", msg);
    c = strdup(msg);  
    printf("In dup_test, c is %s\n", c);  
}

运行此程序,结果为

In main, the address of c is 0x7ff7bf29a650
In dup_test, the address of c is 0x7ff7bf29a638
origin msg: hello world

In dup_test, c is hello world

[1]    31055 segmentation fault  ./trial_string_c

字符指针c 并没有指向strdup()函数分配的内存。可以看到在main函数中和dup_test()函数中,变量c的地址不同,这是因为在C语言中函数是值传递。

当在main函数中定义了一个char*类型的变量时,系统为其分配了4个字节(64位系统中分配8个字节)内存,默认其初始值为NULL。也就是说,在这四个字节的内存中,存储的是NULL。当向函数传递时,传递的是NULL

正确的做法是,将strdup_test(char *s)声明中的参数改为二级指针,调用此函数的时候传入s的地址。


版权声明:本文为weixin_43772677原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。