1 overview
A struct is a structure that can contain different data types, which is a type of data that can be defined by itself.
2 Methods for defining struct type variables
the general format for defining struct-body variables is:
struct structure name
{
Type variable name;
type variable name;
...
} structure variables;
The code is as follows:
struct student{char name[8]; int age; }STU1;
The above code declares a struct named student that contains two members name and age, the data type of the member name is an array of characters, the data type bits of the member age are shaped, and a student struct variable stu1 is defined.
Note: The struct declaration itself does not occupy any memory space, and the computer allocates memory only when the struct variable is defined.
struct Student can also be used to construct variable names; Define struct variables in the following way:
struct Student stu2 = {"Lily", 19};
It can also be simplified in typedef form, with the following code:
typedef struct STUDENT mystudent; Mystudent stu3 = {"Jake", 20};
The complete example is as follows:
#include <corefoundation/corefoundation.h>int main (int argc, const char * argv[]) { struct student{ char name[8]; int age; }stu1; typedef struct Student MyStudent; strcpy (stu1.name, "Jackz"); stu1.age = 20; printf ("Name:%s, Age:%d\n", Stu1.name,stu1.age); struct student stu2 = {"Lily", 19}; printf ("Name:%s, Age:%d\n ", stu2.name,stu2.age); mystudent stu3 = { "Jake", 20}; printf ("Name:%s, Age:%d\n", stu3.name,stu3.age); return 0;}
Results such as:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/46/67/wKiom1PyIUbBiLvHAAB76jdhnPY910.jpg "title=" struct uses. png "alt=" wkiom1pyiubbilvhaab76jdhnpy910.jpg "/>
Extension: Simple use of linked lists
#include <corefoundation/corefoundation.h>int main (int argc, const char * argv[]) { typedef struct _node{ float score; int age; struct _Node *next; }Node; Node node1,node2,node3; node1.score = 60.5; node1.age = 18; node2.score = 80.4; node2.age = 19; node3.score = 100.2; node3.age = 20; node1.next = &node2; node2.next = &node3; node3.next = 0; node curnode = node1; printf ("Score:%.1f, Age:%d\n", CurNode.score, Curnode.age); do { curnode = *curnode.next; printf ("Score:%.1f, Age:%d\n", CurNode.score, Curnode.age); }while (curnode.next); return 0;}
The results are as follows:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/46/6A/wKioL1PyJnejygTqAAB9Zjxws4w418.jpg "title=" Use of the linked list. png "alt=" wkiol1pyjnejygtqaab9zjxws4w418.jpg "/>
This article is from the "7803002" blog, please be sure to keep this source http://7813002.blog.51cto.com/7803002/1541817