Bionix1441 Bionix1441 -4 years ago 90
C Question

Why do we need pointer to a structure pointer to change members value?

While for simple types

(simple types: int, char..)
we directly use pointers
(their address)
as an argument to a function to permanently change their value in the main program, can someone explain to me why for structures we need a pointer to a
Structure pointer
, and not just a pointer?

struct someStruct
{
int field1;
int field2;
}

void initializeFields(struct someStruct** foo)
{
//changing fields
}

//while
void initializeFields(struct someStruct* foo) //does not work ?

Answer Source

To only change the members of the structure you don't need that. But to change the actual pointer to the structure you need to emulate pass by reference by using pointer to a pointer to the structure.

For example, to only change a member this is enough

void initializeFields(struct someStruct* foo)
{
    foo->field1 = 1;
    foo->field2 = 2;
}

int main(void)
{
    struct someStruct bar;
    initializeFields(&bar);
    printf("field1 = %d\n", bar.field1);
    printf("field2 = %d\n", bar.field2);

    return 0;
}

But if you for example want to dynamically allocate the structure in the function you need to emulate pass by reference:

void initializeFields(struct someStruct** foo)
{
    // The difference is this assignment
    *foo = malloc(sizeof(struct someStruct));

    (*foo)->field1 = 1;
    (*foo)->field2 = 2;
}

int main(void)
{
    struct someStruct* bar;
    initializeFields(&bar);
    printf("field1 = %d\n", bar->field1);
    printf("field2 = %d\n", bar->field2);

    return 0;
}

Two more examples to show the difference between pass by value and emulating pass by reference.

Consider the following program:

#include <stdio.h>

void foo(int y)
{
    y = 5;
}

int main(void)
{
    int x = 1;
    printf("1: x = %d\n", x);
    foo(x);
    printf("2: x = %d\n", x);

    return 0;
}

The above program will print

1: x = 1
2: x = 1

That is because a copy of the value in x is passed to the function foo. Modifying the local copy inside foo will not modify the original variable x inside main.

Now to emulate pass by reference:

#include <stdio.h>

void foo(int *y)
{
    *y = 5;
}

int main(void)
{
    int x = 1;
    printf("1: x = %d\n", x);
    foo(&x);
    printf("2: x = %d\n", x);

    return 0;
}

This program will print

1: x = 1
2: x = 5

This is because we don't change the pointer variable y inside the function foo, but we change the value of where it points, which happens to be the variable x in the main function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download