elaborated on ptr to structs and typedef usage (#30511)

This commit is contained in:
stavkl
2019-06-09 04:15:13 +03:00
committed by Christopher McCormack
parent 08e9c650d9
commit 5fb6d5fd6b

View File

@ -19,7 +19,7 @@ struct StudentRecord
char Phone[10];
};
```
* We can also define a **structure** using **typedef** which makes initializing a structure later in our program easier.
* We can also define a **structure** using **typedef** which makes initializing a structure later in our program easier. Note that using typedef requires naming the structure, in the example below **struct StudentRecord** was given the name **Record**.
```C
typedef struct StudentRecord
{
@ -36,7 +36,8 @@ int main(void)
struct StudentRecord student1;
}
```
And using **typedef**, the user-defined data-type looks like:
the keyword struct must always precede **StudentRecord**, as it was not defined as a type.
Using **typedef**, only the given name is sufficient to declare a type, so the user-defined data-type looks like:
```C
int main(void)
{
@ -59,5 +60,29 @@ int main(void)
printf("Name: %s \n, Class: %d \n, Address: %s \n, Phone: %s \n",student1.Name, student1.Class, student1.Address, student1.Phone);
}
```
We can also dynamically allocate memory for a struct, as follows:
```C
Record *student1Ptr = (Record *)malloc(sizeof(Record));
//always check for null after malloc
```
This will make malloc calculate the size of all the elements in the struct and allocate the appropriate amount of memory accordingly. To access members of a struct's pointer we use an arrow `->`
```C
int main(void)
{
Record *student1Ptr = (Record *)malloc(sizeof(Record));
//check for null
student1Ptr->Class = 10;
printf("Enter Name of Student\n");
scanf("%s",student1Ptr->Name);
printf("Enter Address of Student\n");
scanf("%s",student1Ptr->Address);
printf("Enter Phone Number of Student\n");
scanf("%s",student1Ptr->Phone);
// Printing the Data
printf("Name: %s \n, Class: %d \n, Address: %s \n, Phone: %s \n",student1->Name, student1->Class, student1->Address, student1->Phone);
free(student1Ptr);
}
```
### More Information
https://www.tutorialspoint.com/cprogramming/c_structures.htm