c - 我是否更改函数中的原始指针地址?
问题描述
我有一个关于指针的一般问题。就像我调用一个函数,例如第一个参数是一个指针。如果我用指针++更改函数中的指针地址,我是在一般情况下更改指针还是只是像副本一样,并且在调用它的函数中,指针具有与调用之前相同的地址。
我希望这是可以理解的:)
谢谢
解决方案
在 C 中,所有参数都是按值传递的,甚至是指针。这意味着如果您将指针传递给函数,则该指针将被复制,并且该函数将具有一个本地副本,它可以根据需要进行修改而不会影响原始指针。
例子:
#include <stdio.h>
void print_pointer_plus_one(const char *pointer)
{
++pointer; // Make pointer point to the next element
printf("In call: %s\n", pointer);
}
int main(void)
{
const char* hello = "hello";
printf("Before call: %s\n", hello);
print_pointer_plus_one(hello);
printf("After call: %s\n", hello);
}
上面的程序应该打印
Before call: hello
In call: ello
After call: hello
您调用的函数可以修改指针指向的数据,这将影响数据本身而不是指针。这可用于模拟通过引用传递:
#include <stdio.h>
void modify_data(char *pointer)
{
pointer[0] = 'M'; // Modify the data that pointer is pointing to
}
int main(void)
{
char hello[] = "hello";
printf("Before call: %s\n", hello);
modify_data(hello);
printf("After call: %s\n", hello);
}
该程序将打印
Before call: hello
After call: Mello
推荐阅读
- aws-api-gateway - 具有多个 API 的 API 网关映射 - 最佳实践
- jquery - JQuery 提交在第一次提交后运行多次
- sql-server - SSRS - 聚合字段的总和
- http - 如何在 Apache Http5 Java 库中重试?
- r - 尽管有足够的内存,但 R 无法分配内存
- http - 使用 Power Automate 将用户添加到 SharePoint 组
- filter - 根据many2one字段的条件设置one2many列表显示的过滤器?(奥多 13)
- php - 如何更改 SimpleXLSXGen 中的第一个工作表名称?
- git - 使用 git instaweb 时如何启用“责备”?
- django - 如何在django rest框架中显示相关商家账户的产品和订单?