Ilia
Ilia

Reputation: 15

How to allocate memory to an pointer passed to a function?

#include <stdio.h>
#include <stdlib.h>

void func(int *newvar);

int main(int argc, char *argv[]) 
{
    int *var;
    func(var);

    system("pause");
    return 0;
}

void func(int *newvar)
{
    int *tmp = malloc(sizeof(int));
    newvar = tmp;
}

After the function has exited, a value of the pointer 'var' did not change. What could be wrong in my code?

Upvotes: 0

Views: 75

Answers (2)

Achal
Achal

Reputation: 11931

After the function has exited, a value of the pointer 'var' did not change ? if you want var to be changed then pass the address of var and in func() catch with double pointer as

int main(int argc, char *argv[]) {
        int *var;
        printf("before in %s : %p\n",__func__,var);
        func(&var); /* pass the address of var */
        printf("after in  %s : %p\n",__func__,var);
        //system("pause");
        return 0;
}

void func(int **newvar) {
        int *tmp = malloc(sizeof(*newvar));
        *newvar = tmp; /* it will change the var in calling function */
        printf(" in  %s : %p\n",__func__,*newvar);
}

Upvotes: 2

aokellermann
aokellermann

Reputation: 71

You have to pass the memory location of var to func like this

func(&var);

Upvotes: 1

Related Questions