#include <stdlib.h>#include<string.h>#defineMAX 16typedefstruct{ intData[max]; intlength;} SqList;voidInit (SqList *L) {SqList*L2; inti =0; L2= (SqList *)malloc(sizeof(sqlist)); L2->length =Ten; for(; I < l2->length; i++) {L2->data[i] = the; } *l = *L2;}voiddisplay (SqList L) {inti =0; for(; i<l.length; i++) {printf ("%d", L.data[i]); }}//******************************************//the address of the parameter passed in as a pointer variablevoidInit2 (sqlist * *L) { inti =0; //returns the first address assigned to the struct and stores it in a pointer variable*l = (SqList *)malloc(sizeof(sqlist)); (*L)->length =Ten; for(; i < (**l). length; i++) { (*L)->data[i] = A; } }voidDisplay2 (SqList *L) { inti =0; for(; i<l->length; i++) {printf ("%d", l->Data[i]); }}int_tmain (intARGC, _tchar*argv[]) {SqList L; Init (&L); Display (L); printf ("\ n"); SqList*PL; Init2 (&PL); Display2 (PL); return 0;}
If the struct is not defined as a pointer variable, the initialization needs to be initialized directly, and if initialized with the Init function, a struct space will be applied again. Reduce efficiency.
So it's best to use pointers.
There are 2 ways to initialize a struct, and you can define the structure as a global variable without malloc allocating space. But generally do not use global variables, so
sqlist* PL; Init2 (&PL); Display2 (PL);
is the best.
Why is a struct generally defined as a pointer variable?