0

What am I doing wrong here? Am I allocating memory to the original charPtr or something else? Why can I read the value of charPtr within func2but not in main (charPtr is NULL in main)?

#include <stdlib.h>
#include <stdio.h>
void func2(char *charPtr)
{
        charPtr = (char *)malloc(sizeof(char));
        *charPtr = 'c';
        printf("func2: %c\n", *charPtr);
}

void func1(char** charDoublePointer)
{
        //*charDoublePointer = (char *)malloc(sizeof(char));
        func2(*charDoublePointer);
}

int main(int argsc, char* argv[])
{
        char * charPtr = NULL;
        func1(&charPtr);

        printf("%c\n", *charPtr);
}
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
Marko Galesic
  • 472
  • 5
  • 17

2 Answers2

1

Function func2 gets a copy of the original pointer. That is the parameter of functioon func2 is a local variable that will be destroyed after exiting the function.

void func2(char *charPtr);

You could define the functions the following way

char * func2()
{
        char * charPtr = (char *)malloc(sizeof(char));
        *charPtr = 'c';
        printf("func2: %c\n", *charPtr);

        return charPtr;
}

void func1(char** charDoublePointer)
{
        //*charDoublePointer = (char *)malloc(sizeof(char));
        *charDoublePointer = func2();
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You're missing one level of indirection. func2 needs to take a char** just like func1. When you write:

void func2(char *charPtr)
{
        charPtr = (char *)malloc(sizeof(char));
        *charPtr = 'c';
        printf("func2: %c\n", *charPtr);
}

You're just assigning the local variable charPtr, which has no effect on the outside program. Instead, write:

void func2(char **charPtr)
{
        *charPtr = malloc(sizeof(char)); //don't cast result of malloc
        **charPtr = 'c';
        printf("func2: %c\n", **charPtr);
}

Change the name to charDoublePtr if you insist.

And call it in func1 like:

func2(charPtr);
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79