Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why double-pointer for structure

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
Hi,

Suppose I have this struct:

[begin code]
typedef struct {
int a;
int b;
struct c; // c is another structure defined somewhere
} mystruct;

mystruct **s; // double pointer declaration
[end code]

I am wondering the reason to use double pointer of s is because of the existence of "struct c", right? otherwise I can use single pointer, correct?

 
'Double' pointer has nothing to do with struct c.

Most? often you will use this if you want a 'child' function to create a structure, and further want the child to pass the address of the created structure into a location (address)decided by the calling function.

The parent calls the child with the address of the pointer. Within the child, the parameter is the address of a pointer - what you call a double pointer.


#include <stdio.h>

typedef struct {
int a;
int b;
//struct c; // c is another structure defined somewhere
} mystruct;


void parent(void);
void child(mystruct ** pp);

int main(void)
{
parent();
return 0;
}

void parent(void)
{
mystruct * pM;
child(&pM); /* Address of pointer */
printf(&quot;\npM -> a = %d&quot;, pM -> a);
free(pM);
}

void child(mystruct ** pp)
{
*pp = (mystruct*)malloc(sizeof(mystruct));
memset(*pp, 0, sizeof(mystruct));
(*pp) -> a = 22;
}

/JOlesen
 
Hi,

I posted it too fast: the 'double-pointer' is actually for a struct array: eg. *mystruct[10].

thanks anyway.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top