Kousaka Kirino
Kousaka Kirino

Reputation: 139

What is the syntax of a pointer to a pointer?

Let's say I have two structures,

struct ptr1
{
    struct ptr2 *ptrtoptr;
};

struct ptr2
{
    int name;
};

Main function looks like this:

int main()
{
    struct ptr1 *var1;
    struct ptr2 *var2;

    (code for manipulating structure element name);

    return 0;
}

How do a manipulate data of variable name via pointer var1? Let's say both pointers are already pointed at a certain address.

Is this correct? var1->(var2->name)=(some value) or (var1->var2)->name=(some value)?

Upvotes: 4

Views: 70

Answers (2)

P0W
P0W

Reputation: 47794

How do a manipulate data of variable name via pointer var1 ?

Using :

var1->ptrtoptr->name =  some_value ; // or (var1->ptrtoptr)->name

Neither of var1->(var2->name)=(some value) or (var1->var2)->name=(some value) make sense since var2 is not a member of ptr1, which can't be accessed using var1


Note: Also, be cautions about the operator associativity , operator -> has left to right associativity, therefore var1->(ptroptr->value) will not be same as var1->ptrtoptr->name

Upvotes: 7

Anthony Korzan
Anthony Korzan

Reputation: 63

I would say it is very important to write functions that will help allocate and free your structures. This will help prevent memory leaks and what not. I wrote a sample program to show what I mean. The other best answer accurately answers your question, I just wanted to add my two cents.

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

struct ptr1
{
    struct ptr2 *ptrtoptr;
};

struct ptr2
{
    int name;
};

struct ptr1* createPtr1() {
    struct ptr1* var1 = (struct ptr1 *) malloc(sizeof(struct ptr1));
    var1->ptrtoptr = (struct ptr2 *) malloc(sizeof(struct ptr2));

    return var1;
}

void freePtr1(struct ptr1* var1) {
    free(var1->ptrtoptr);
    free(var1);
}

int main()
{
    struct ptr1 *var1;
    struct ptr2 *var2;

    var1 = createPtr1();
    var1->ptrtoptr->name = 42;

    printf("%d\n", var1->ptrtoptr->name);
    freePtr1(var1);

    return 0;
}

Upvotes: 0

Related Questions