Why are structs generally defined as pointer variables?

Source: Internet
Author: User

#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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.