Chapter 14 structure and other data forms

Keywords: Java Programming less

1, Structure

The structure is similar to the class in java, but it only has properties and no methods

1.1 define, declare, initialize structure, access structure members

#include <stdio.h>
#define	SIZE 20

//Defining structure
struct book
{
	char name[SIZE];
	char author[SIZE];
	double price;
};

int main(void)
{
    //Declaring structure
	struct book book_b;
	struct book book_c;

	//Declaration structure is initialized at the same time
	struct book book_a = {
		"C Primer Plus",
		"Stephen Prata",
		60
	};

	//Use the initializer to initialize. This method will initialize the specified members. Other members use the default value
	struct book book_d = {
		.author = "d"
	};		

	//Use the method of accessing structure members for initialization, which will cause memory leak if accessing uninitialized properties
	gets_s(book_c.name, SIZE);
	gets_s(book_c.author, SIZE);
	book_c.price = 50;

	//Initialize one structure to another
	book_b = (struct book){
		"b",
		"B",
		60
	};

	printf("book_a: \n");
	printf("name: %s, author: %s, price: %.2f", book_a.name, book_a.author, 		book_a.price);
	printf("\n--------------------------------\n");

	printf("book_b: \n");
	printf("name: %s, author: %s, price: %.2f", book_b.name, book_b.author,           book_b.price);
	printf("\n--------------------------------\n");

	printf("book_c: \n");
	printf("name: %s, author: %s, price: %.2f", book_c.name, book_c.author, book_c.price);
	printf("\n--------------------------------\n");

	printf("book_d: \n");
	printf("name: %s, author: %s, price: %.2f", book_d.name, book_d.author, book_d.price);
	printf("\n--------------------------------\n");

	getchar();

}

/*Operation result
c
C
book_a:
name: C Primer Plus, author: Stephen Prata, price: 60.00
--------------------------------
book_b:
name: b, author: B, price: 60.00
--------------------------------
book_c:
name: c, author: C, price: 50.00
--------------------------------
book_d:
name: , author: d, price: 0.00
--------------------------------
*/

Code details:

Structure has two meanings. The first meaning is "structure layout", which tells the compiler how to represent data, but it does not let the compiler allocate space for data. Another meaning is structure variable. Create a structure variable:

​ struct book book_a;

When the compiler executes this line of code, it creates a structure variable, book a. The compiler uses the book template to allocate space for this variable: two char arrays containing SIZE elements and a variable of type double.

1.5 structure array

Structure array is a structure stored in an array.

Example:

#include <stdio.h>
#define SIZE 20

struct book
{
        char name[SIZE];
        char author[SIZE];
        double price;
};

int main(void)
{
        int i;
    	//Create structure array
        struct book books[SIZE] =
        {
                {"aa", "AA", 20.5},
                {"bb", "BB", 30},
                {"cc", "CC", 40}
        };

    	//Output array
        printf("%15s %15s %15s\n", "name", "autor", "price");
        for(i = 0; i < 3;  i++)
                printf("%15s %15s %13.2f\n", books[i].name, books[i].author, 	 books[i].price);

        return 0;
}
/*Operation result
 name           autor           price
 aa              AA         20.50
 bb              BB         30.00
 cc              CC         40.00
 */

1.6 pointer to structure

This example demonstrates two methods:

I. point the pointer to a declared structure

Using malloc to allocate space for pointers

Example 1:

#include <stdio.h>
#define SIZE 20

struct book
{
        char name[SIZE];
        char author[SIZE];
        double price;
};


int main(void)
{
        struct book book_a ={
                "C Primer Plus",
                "Stephen Prata",
                60
        };
        //Declaration structure pointer
        struct book * book_ptr_a;
        struct book * book_ptr_b;

        //Pointer to book a
        book_ptr_a = &book_a;
		//output
        printf("%15s %15s %15s\n", "name", "autor", "price");
        printf("%15s %15s %13.2f\n", book_ptr_a->name, book_ptr_a->author, book_ptr_a->price);
        return 0;
}
/*Result
name           autor           price
C Primer Plus   Stephen Prata         60.00
*/

Example 2:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 20

struct book
{
        char name[SIZE];
        char author[SIZE];
        double price;
};

int main(void)
{
        struct book* book_ptr_b;
        double* p = (double *) malloc(5 * sizeof(double));
        //Using malloc to allocate space
        book_ptr_b = (struct book*) malloc(sizeof(struct book));
        //set a property
        scanf("%s%s", book_ptr_b->name, book_ptr_b->author);
        book_ptr_b->price = 50;
              
        printf("%15s %15s %15s\n", "name", "autor", "price");
        printf("%15s %15s %13.2f\n", book_ptr_b->name, book_ptr_b->author, book_ptr_b->price);
    	//The space allocated by malloc will not be released automatically. Develop good programming habits and use free to release space
    	free(p);

        return 0;
}
/*Operation result
bb cc
name           autor           price
bb              cc         50.00
*/

Example 3: scalable array member, that is, the array in the structure is not initialized when it is defined

#include <stdio.h>
#include <stdlib.h>

struct class
{
        int grade;
        int stdunts[];  //Length of stdunts not specified
};

int main(void)
{
    	//Declare and initialize a structure class with length less than 5 for students
        struct class * c = (struct class *) malloc(sizeof(struct class) + 5 * sizeof(int));
    	
    	free(c);

        return 0;
}

1.7 transfer structure information to function

There are three types of information that can be delivered:

I. transfer structure members

II. Transfer structure pointer (by address)

III. transfer a structure (transfer by value)

1.8 use malloc() to allocate memory for pointer members in the structure

Example:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 20

struct book
{
        char * name;	//name is a pointer that stores the address of the string
        char * author;
        double price;
};

int main(void)
{
        //Declare a book Structure
        struct book mybook;

        //Allocate memory pointed to by name  
        mybook.name = (char *) malloc(SIZE);
        //Allocate the memory pointed by the author        
        mybook.author= (char *) malloc(SIZE);

        //Set a value for the memory pointed to by name
        scanf("%s %s", mybook.name, mybook.author);

        //Output value
        printf("%s, %s\n", mybook.name, mybook.author);
        return 0;
}
/*Operation result
aaa AAA(Input)
aaa, AAA (Output)
*/

1.10 save structure to file

/*fwrite Save structure to file, note: binary format is saved to file*/
#include <stdio.h>
#define SIZE 20

//Define structure
struct book
{
        char name[SIZE];
        char author[SIZE];
        double price;
};

int main(void)
{
        FILE *bookfile;
        int i;
        //Define an array of structures
        struct book books[3] = {
                {"aa", "AA", 20},
                {"bb", "BB", 30},
                {"cc", "CC", 40}
        };

        bookfile = fopen("books", "wb");
        fwrite(books, sizeof(struct book), 3, bookfile);        //Write the contents of the array to the bookfile file

        fclose(bookfile);

        return 0;
}
/*Read structure from file using free()*/
#include <stdio.h>
#define SIZE 20

//Define a structure
struct book
{
        char name[SIZE];
        char author[SIZE];
        double price;
};

int main(void)
{
        int i;
        FILE *bookfile;         //field name pointer
        struct book books[3];   //Structure array

        bookfile = fopen("books", "rb");        //Open books
        fread(books, sizeof(struct book), 3, bookfile); //Read the contents of the file into the structure array 

        //output
        printf("books: \n");
        for(i = 0; i < 3; i++)
                printf("name: %s, author: %s, price: %.2f\n", books[i].name, books[i].author, books[i].price);

        return 0;
}
/*Result:
books: 
name: aa, author: AA, price: 20.00
name: bb, author: BB, price: 30.00
name: cc, author: CC, price: 40.00
*/

2, union

Federation is a data type that can store different data types in the same memory space (not at the same time).

2.1 joint use

Example:

#include <stdio.h>

//Define a union
union data {
        int a;
        double b;
};

int main(void)
{
        //Statement joint
        union data a = {88};            //Initialize union members
        union data b = {.b = 55.5};     //Initializing element b with initializer
        union data c;

        //View data
        printf("union a: \n");
        printf("a = %d, b = %.2f\n", a.a, a.b);

        printf("union b: \n");
        printf("a = %d, b = %.2f\n", b.a, b.b);

        printf("union c: \n");
        c.a = 1;
        printf("before set b, a = %d, b = %.2f \n", c.a, c.b);
        c.b = 2;
        printf("after set b, a = %d, b = %.2f \n", c.a, c.b);

        //View Federation size
    	printf("--------------------------------\n");
        printf("size of union: %zd\n", sizeof(union data));

        return 0;
}
/*Operation result
union a: 
a = 88, b = 0.00
union b: 
a = 0, b = 55.50
union c: 
before set b, a = 1, b = 0.00 
after set b, a = 0, b = 2.00 
--------------------------------
size of union: 8
*/

Analysis results:

The experimental results meet the definition. Only one variable can be stored in the union, and other variables are the default values. The size of the space occupied by the Federation is the space occupied by the largest data type.

3, Enum (enum)

Integer constants can be represented by enumerating type declaration symbol names. The purpose of enumeration type is to improve the readability of program.

Example:

#include <stdio.h>

enum spectrum { red, orange, yellow, green, blue, violet};
int main(void)
{
        enum spectrum color;
		
    	//View values for enumeration
        printf("red = %d, orange = %d, yellow = %d, green = %d, blue = %d, violet = %d\n", red, orange, yellow, green, blue, violet);

        color = 1;      //Assign color with an integer constant
        switch(color)
        {
                case 0: printf("I'm red\n");
                        break;
                case orange: printf("I'm orange\n");    //Use enumeration to accept integer constants
                             break;

                default: printf("I'm others");
                         break;
        }

        return 0;
}
/*Operation result
red = 0, orange = 1, yellow = 2, green = 3, blue = 4, violet = 5
I'm orange
*/

4, Function pointer

Ordinary variables have addresses, so do functions. The starting address of the function code is stored in the pointer to the function. The main use of the function pointer is to take the function as the parameter of another function.

Declaring function pointer is the same as declaring function. It also needs to specify name, parameter and return value type.

Example: void (*pf) (char *)

Example 1:

/*Practice declaring and using function pointers*/
#include <stdio.h>

void (*pf) (char *); //Declare a function pointer
void show(char *);      //Declare a function and point to it with a function pointer

int main(void)
{
        pf = show;

        //ANSI considers these two methods equivalent
        pf("I'm 'pf'");
        (*pf)("I'm '*pf'");

        return 0;
}

void show(char * str)
{
        printf("%s\n", str);

        return;
}
/*Operation result
I'm 'pf'
I'm '*pf'
*/

Example 2:

#include <stdio.h>

void (*pf) (char *); //Declare a function pointer
void show(char *);      //Declare a function and point to it with a function pointer
void usePf (void (*pf)(char *), char *, int choice);    //Declare a function whose parameter is a function pointer, a char * and an int value whose parameter is char *

int main(void)
{
        pf = show;
        int choice;
        char str[20];

        //Write a loop to accept the user's choice, and stop when the input is not a number
        printf("enter your choice: ");
        while(scanf("%d", &choice) == 1)
        {
                printf("enter a string: ");
                scanf("%s", str);

                usePf(pf, str, choice);         //Call usePf
                printf("enter your choice: ");
        }


        return 0;
}

void show(char * str)
{
        printf("%s\n", str);

        return;
}

void usePf(void (*pf)(char *), char * str, int choice)
{
        switch(choice)
        {
                case 1: printf("No.1, ");
                        break;

                case 2: printf("No.2, ");
                        break;

                case 3: printf("No.3, ");
                        break;
        }

        pf(str);        //Use function pointer to call show function
}
/*Operation result
enter your choice: 1
enter a string: hello
No.1, hello
enter your choice: 2
enter a string: chi
No.2, chi
enter your choice: 3
enter a string: hh
No.3, hh
*/

Reference books

C Primer Plus (6th Edition) Chinese version

Published 11 original articles, won praise 0, visited 223
Private letter follow

Posted by sneha1234 on Sun, 02 Feb 2020 03:22:55 -0800