Updating pointers in a function

asicman picture asicman · Apr 15, 2015 · Viewed 10k times · Source

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\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;
}

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

Answer

Iharob Al Asimi picture Iharob Al Asimi · Apr 15, 2015

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  );
}

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.