c - 为什么 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
指针不一样吗?p
func
解决方案
C 不是按引用传递,所以当你写到p
in时func
,你写的是func
' 的副本p
,而不是main
' 的副本。
p
作为指向 的指针传递func
,但您正在尝试修改指针本身。您需要将指针传递给要修改的指针p
。
要解决此问题,请将指向的指针传递p
给func
,如下所示:
#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
}
推荐阅读
- javascript - HTML 单选按钮总是将最后一个选项提交给 PHP
- php - 使用代理的php套接字连接
- prolog - 如何摆脱序言中的重复项?
- java - 从大型未排序数组中删除重复项并保持顺序
- nginx-location - 为HTTP流量配置Nginx的反向代理出现403
- c# - 如何在新数据列中设置格式日期时间
- docker - Docker 容器失败,找不到文件
- javascript - 无法从 jquery 函数在 textarea 中添加###Name###
- python - pandas groupby 中未来行的条件搜索
- amazon-web-services - SES 模板/电子邮件无法呈现日文文本