Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c - Updating pointers in a function

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.

Here is my code:

#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
", 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
", pSrc  );

    func(pSrc);

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

    return EXIT_SUCCESS;
}

Here is the output

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.

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 :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", pSrc  );
}

and

func(&pSrc);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...