1

Displaying the value to which a pointer referred in the local function makes sense for me, calling this local function in the main function, the value to which the pointer refered changed.

#include<stdio.h>

char *getAnotherString(){

    char target[] = "Hi, ComplicatedPhenomenon";
    char *ptrToTarget = target;

    printf("ptrToTarget                 = %p\n", ptrToTarget);
    printf("ptrToTarget                 = %s\n", ptrToTarget);
    return ptrToTarget;

}

int main(){
    char *ptrToTarget = NULL;
    ptrToTarget = getAnotherString();
    printf("ptrToTarget                 = %p\n", ptrToTarget);
    printf("ptrToTarget                 = %s\n", ptrToTarget);

    return 0;
}

I expected the output like

ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon

the actual output is

ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedP
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45

2 Answers2

3
char target[] = "Hi, ComplicatedPhenomenon";

is a local character array. This means that it becomes invalid once the function ends and you should not be using it later on. Doing so will invoke Undefined Behavior which means that the output could be anything.

You can fix it by dynamically allocating memory using malloc or use a static array.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

I don't have much experience on c language but I think this is about memory scope. variables allocated with char[] is stored on stack. (I just googled for it quickly, and it actually seems to be dependent to compiler) So after function is returned, pointer has no real value.

But if you define ptrToTarget as char * like this, char * ptrToTarget = "..."; this gonna work as you expected.

Jay Kim
  • 123
  • 1
  • 11
  • Yes, it works as you said when I directly initialize the pointer like this`char *ptrToTarget = "Hi, ComplicatedPhenomenon";`, but why this function returned a pointer with real value, shouldn't `Hi, ComplicatedPhenomenon` also be destroyed when function returned – ComplicatedPhenomenon Mar 30 '19 at 07:45
  • 1
    What really is in the returned pointer of the function is just a garbage value. It had been destroyed when the function returned because it is stored in the stack. Mean while if you declare char* str="..."; then str is stored in a global scope, like text area or something. – Jay Kim Mar 30 '19 at 09:15