更新函数中的指针 [英] Updating pointers in a function

查看:88
本文介绍了更新函数中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向指针传递一个对其进行更新的函数.但是,当函数返回指针时,它将返回到函数调用之前的值.

I am passing a pointer a function that updates it. However when the function returns the pointer it returns to the value it had prior to the function call.

这是我的代码:

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

static void func(char *pSrc) {
    int x;
    for ( x = 0; x < 10; x++ ) {
        *pSrc++;
    }

    printf("Pointer Within Function: %p\n", pSrc  );
}

int main(void) {

    char *pSrc = "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson.";

    printf("Pointer Value Before Function: %p\n", pSrc  );

    func(pSrc);

    printf("Pointer Value After Function: %p\n", pSrc  );

    return EXIT_SUCCESS;
}

这是输出

Pointer Value Before Function: 0x100403050
Pointer Within Function: 0x10040305a
Pointer Value After Function: 0x100403050

我期望的是函数后的值与函数中的值相匹配.

What I was expecting was the value after the function to match the one from within the function.

我尝试切换到char **pSrc,但效果不理想.

I tried switching to char **pSrc but that did not have the desired affect.

我确信答案很简单,但是我是一位正在恢复的硬件工程师,似乎无法弄清楚:-)

I am sure the answer is fairly simple, but I am a recovering hardware engineer and can't seem to figure it out :-)

推荐答案

函数内部的指针是传递的指针的副本.

The pointer inside the function is a copy of the passed pointer.

它们拥有相同的地址,但具有不同的地址,因此更改其中一个拥有的地址不会影响另一个.

They both hold the same address but have different addresses, so changing the address held by one of them doesn't affect the other.

如果您想在函数内部增加指针,则改为传递其地址,就像这样

If you want to increment the pointer inside the function pass it's address instead, like this

static void func(char **pSrc) {
    int x;
    for ( x = 0; x < 10; x++ ) {
        (*pSrc)++;
    }    
    printf("Pointer Within Function: %p\n", pSrc  );
}

func(&pSrc);

另外,请注意不要修改内容,因为您的指针指向字符串文字,并且字符串文字不能被修改.

Also, be careful not to modify the contents, because your pointer points to a string literal, and string literals cannot be modified.

这篇关于更新函数中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆