Copacel
Copacel

Reputation: 1390

Pointer as a parameter in C

Let's say a have a pointer as a parameter, why doesn't it's value remain modified after the and of a function, and i have to use this syntax :

void function_name (int **p)
{
// code
}

and in main() :

int *v;

function name (&v);

I want to specify that i use a pointer to a struct type as a parameter.

Upvotes: 3

Views: 10239

Answers (2)

lost_in_the_source
lost_in_the_source

Reputation: 11237

In C, arguments are passed by value. This means that when you pass an argument to a function, a copy of that variable is made. For example

int main()
{
    int x = 6;
    repchar(x, 'r');

    printf("%d\n", x);
    return 0;
}
void repchar(int n, char c)
{
    while (--n >= 0)
        putchar(c);
}

This program prints the letter r six times, and then at the last printf, prints out 6, not -1. The reason is that when repchar was called, x was copied. That way, when repchar decrements n, the caller's copy is not changed.

If we passed a pointer, however, n would be modified.

int main()
{
    int x = 6;
    repchar(&x, 'r');

    printf("%d\n", x);
    return 0;
}
void repchar(int *n, char c)
{
    while (--(*n) >= 0)
        putchar(c);
}

Instead of the variable being copied, now the address of the variable is being copied. Inside of repchar, *n is being counted down. This accesses the value that is being referenced by n, which is the same address as x and decrements it. As a result, the last printf will give -1.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206667

C passes arguments by value. If you want to modify something in a function and make the modification take effect in the calling function, a pointer to the variable in the calling function has to be passed. Otherwise, any changes made to the variable in a function are only local changes and does not affect the value of the variable in the calling function.

Let's start with an int type variable.

void foo(int x)
{
   x = 10;
}

int main()
{
   int a = 100;
   foo(a);  // Value of a does not change in this function
}

In the above program, the value of a remains 100 in main. The line

x = 10;

in foo only affects the value of the variable in foo. To make the change in foo affect the value in main, you'll need to pass a pointer to a.

void foo(int* x)
{
   *x = 10;
}

int main()
{
   int a = 100;
   foo(&a);  // Value of a changes in this function
}

Take that analogy to a pointer.

void bar(int* x)
{
   x = malloc(10*sizeof(int));
}

int main()
{
   int* ptr = NULL;
   bar(ptr);  // Value of ptr does not change in this function
}

bar allocates memory for an array of 10 ints and assigns the memory to x but that change is local. main does not see it. In main, ptr is still NULL. To make the change in bar affect ptr, a pointer to ptr has to be passed to bar.

void bar(int** x)
{
   *x = malloc(10*sizeof(int));
}

int main()
{
   int* ptr = NULL;
   bar(&ptr);  // Value of ptr changes in this function
}

Upvotes: 10

Related Questions