Recognize the struct in C and the C struct.
I have introduced the basic knowledge of struct in C, and I will review it through this Code:
1 # include <stdio. h> 2 # define LEN 20 3 4 struct Student {// define struct 5 char name [LEN]; 6 char address [LEN]; 7 int age; 8 }; 9 10 int main (int argc, char * argv []) 11 {12 struct Student s = {// initialize 13 "bluemsun", "NENU", 2514 }; 15 16 struct Student * p; // defines a pointer to the struct 17 p = & s; // assign a pointer to 18 19 printf ("s. name = % s, s. address = % s, s. age = % d \ n ", s. name, s. address, s. age); 20 printf ("p-> name = % s, p-> address = % s, p-> age = % d \ n", p-> name, p-> address, p-> age); 21}
This is a simple example program. In the Student structure, we define two char arrays. Now we will consider this issue. When we usually use arrays, we can use pointers instead of arrays as parameters. Can we use the following code to replace struct definitions in the above program?
1 struct new_Student {// defines the struct 2 char * name; 3 char * address; 4 int age; 5 };
The answer is yes, but there may be some trouble. Consider the following code:
1 struct new_Student s1 = {"zhouxy","EFGH",25}; 2 struct Student s2 = {"bluemsun","ABCD",26};
This code is correct. But where are the strings stored? For the struct Student variable s2, the string is stored inside the structure, which is allocated 40 bytes in total to store two strings. However, for the new_Student variable s1, strings are stored anywhere the compiler stores string constants. The new_Student structure only contains two addresses. Therefore, if you need a structure to store strings, use character array members. So is it true that the memory allocation cannot be completed using pointers? The answer is no. Here I will explain about the Function malloc () in C, which can dynamically allocate memory at runtime. So if we can use it here, we can achieve our vision. Consider the following code:
1 # include <stdio. h> 2 # include <string. h> 3 # include <stdlib. h> 4 5 struct new_Student {// defines the struct 6 char * name; 7 char * address; 8 int age; 9}; 10 11 int main (int argc, char * argv []) 12 {13 char str [] = "zhouxy"; 14 struct new_Student s1; 15 // allocate the memory for storing the name 16 s1.name = (char *) malloc (strlen (str) + 1); 17 // copy the name to 18 strcpy (s1.name, str) in the allocated memory ); 19 20 printf ("s1.name = % s \ n", s1.name); 21}
The above code is correct. We use the malloc () function to allocate the bucket, and then copy the string to the newly allocated space. It should be understood that the name string is not stored in the structure, but stored in the memory managed by the malloc () function. The structure only saves the address of the name string. Another thing to remember is: after we use the malloc () function to allocate memory, we need to call the free () function, otherwise it may cause "Memory leakage ".