首页 > 解决方案 > 为什么 main 函数和 func 函数的 char 指针 p 的输出不同?

问题描述

由于指针p是按指针传递的,所以输出不应该main"Hi there"吗?

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

void func(char *);

int main() {
    char *p = "Hello";
    func(p);
    puts(p);   //Hello <-- Shouldn't this be Hi there
    return 0;
}

void func(char *p) {
    p = (char *)malloc(100);
    strcpy(p, "Hi there");
    puts(p);  //Hi there  
}

传递给函数的指针与函数内部的func指针不一样吗?pfunc

标签: cpointers

解决方案


C 不是按引用传递,所以当你写到pin时func,你写的是func' 的副本p,而不是main' 的副本。

p作为指向 的指针传递func,但您正在尝试修改指针本身。您需要将指针传递给要修改的指针p

要解决此问题,请将指向的指针传递pfunc,如下所示:

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

void func(char **);

int main(void) // int main(void) is more up-to-date
{
    char *p = "Hello";
    func(&p); // pass a pointer to p
    puts(p); // Hi there
    free(p); // free memory that you've allocated
    return 0;
}

void func(char **pp) // char ** for pointer-to-pointer
{
    *pp = malloc(100); // don't cast the result of malloc()
    strcpy(*pp, "Hi there"); // formatting, use *pp instead of p
    puts(*pp); // Hi there
}

推荐阅读