首页 > 解决方案 > 我是否更改函数中的原始指针地址?

问题描述

我有一个关于指针的一般问题。就像我调用一个函数,例如第一个参数是一个指针。如果我用指针++更改函数中的指针地址,我是在一般情况下更改指针还是只是像副本一样,并且在调用它的函数中,指针具有与调用之前相同的地址。

我希望这是可以理解的:)

谢谢

标签: cpointers

解决方案


在 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

推荐阅读