Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...