Pointers,structure C

48 views Asked by At

How can I work with the structure if i pass structure like parameter function ** ?

typedef struct TQueue
{
    ...
    int m_Len;
}TQUEUE;

void nahraj(TQUEUE **tmp)
{
    tmp[5]->m_Len = 7;
}

int main (void)
{
    TQUEUE *tmp;
    tmp = malloc(10*sizeof(*tmp));
    nahraj (&tmp);
    printf("%d\n",tmp[5].m_Len);
}
2

There are 2 answers

0
Barmar On BEST ANSWER

You need to dereference tmp before indexing it, since it's a pointer to an array, not an array itself.

And the elements of the array are structures, not pointers to structures, so you use . rather than ->.

void nahraj(TQUEUE **tmp)
{
    (*tmp)[5].m_Len = 7;
}
0
Vlad from Moscow On

The function should be declared like

void nahraj(TQUEUE *tmp, size_t i, int value )
{
    tmp[i]->m_Len = value;
}

and called like

nahraj( tmp, 5, 7 );

There is no sense to pass the pointer tmp by reference to the function (through a pointer to the pointer tmp) because the original pointer is not changed within the function.

As for your function definition then at least you need to write within the function

( *tmp )[5]->m_Len = 7;

Otherwise the function will invoke undefined behavior because this expression tmp[5] within the function means that the pointer tmp points to an array of pointers to objects of the type TQUEUE. But this is not true.