Struct, struct variable, struct pointer, string

structural morphology

Array is used to save a group of data of the same type, while structure is used to save a group of arrays of different types
Before using a structure, you must first define the structure type, because C language doesn't know what types of data you need to store in your structure. We must tell C language what types of data we need to store in our structure by defining the structure type

struct Structure name{
     Type name 1 member name 1;
     Type name 2 member name 2;
     ......
     Type name n member name n;
 };

Storage space occupied by structure variables

  struct Person{
        int age; // 4. Open up 8byte for the first time, and there are 4 left
        char ch; // 1. Do not use the remaining 4 bytes opened for the first time, and 3 are left 
        double score; // 8 3byte s is not enough for allocation, and 8byte s will be opened for the second time
    };
   struct Person p;
   printf("sizeof = %i\n", sizeof(p)); // 16
The largest memory consuming attribute is score, 8 bytes, So 8 bytes will be allocated for the first time
 Allocate the first allocated 8 bytes to age4 individual,Assigned to ch1 individual, There are three bytes left
 When needed, assign to score Time, It is found that there are only 3 bytes left, So it will open up 8 bytes of storage space again
 Eight bytes of space were opened up twice, So eventually p 16 bytes occupied
    struct Person{
        int age; // 4. 88byte s left for the first time
        double score; // 8 is not enough. Open 8byte for the second time 
        char ch; // 1 no left, 8 byte s for the third time
    };
    struct Person p;
    printf("sizeof = %i\n", sizeof(p)); // 24
The largest memory consuming attribute is score, 8 bytes, So 8 bytes will be allocated for the first time
 Allocate the first allocated 8 bytes to age4 individual,There are four bytes left
 When needed, assign to score Time, Found only 4 bytes left, So it will open up 8 bytes of storage space again
 Allocate the newly allocated 8 bytes to score, 0 bytes left
 When needed, assign to ch Time, It is found that the last allocation is no longer available, So it will open up 8 bytes of storage space again
 A total of 8 bytes of space were opened up three times, So eventually p Occupy 24 bytes

Definition of structure variables

Define structure variable: struct structure name structure variable name;

First define the structure type, and then define the variable:

struct Student {
     char *name;
     int age;
 };
struct Student stu;

Define variables while defining structure types

struct Student {
    char *name;
    int age;
} stu;

Anonymous struct defines a struct variable

struct {
    char *name;
    int age;
} stu;

The difference between the third method and the second method is that in the third method, the structure type name is omitted and the structure variable is given directly,
The biggest problem with this structure is that the structure type cannot be reused.

Initialization of structure variables

Initialize in order while defining

struct Student {
     char *name;
     int age;
 };
struct Student stu = {"cxx", 22};

Defined without sequential initialization

struct Student{
	char *name;
	int age;
};
struct Student stu = {.age = 22, .name = "cxx" };

Define first and then initialize one by one

struct Student{
	char *name;
	int age;
};
struct Student stu;
stu.age = 22;
stu.name = "cxx" ;

Define first and then initialize at one time

struct Student {
     char *name;
     int age;
 };
struct Student stu;
stu2 = (struct Student){"cxx", 22};

Structure pointer

A pointer variable is called a structure pointer variable when it is used to point to a structure variable
Format: = = struct structure name * structure pointer variable name==

int main(void)
{
    // Define a structure type
      struct Student {
          char *name;
          int age;
      };

     // Define a structure variable
     struct Student stu = {"lnj", 18};
     // Defines a pointer variable that points to the structure
     struct Student *p;

    // Point to structure variable stu
    p = &stu;
    
     //At this time, you can access the members of the structure in three ways
     // Method 1: structure variable name member name
     printf("name=%s, age = %d \n", stu.name, stu.age);

     // Method 2: (* pointer variable name) member name
     printf("name=%s, age = %d \n", (*p).name, (*p).age);

     // Method 3: pointer variable name - > member name
     printf("name=%s, age = %d \n", p->name, p->age);

     return 0;
 }

Structure pointer member access

Structure members can be accessed through structure pointers in the following two ways:
(* structure pointer variable) member name
==Structure pointer variable - > member name==

String definition and initialization:

	char string[]="cxx";
	printf("%s\n",string); //Output result: cxx
	//The array name saves the address of the 0th element of the array, and the pointer can also save the address of the 0th element
	char *str = "abc"
	for(int i = 0; i < strlen(str);i++){
  		printf("%c-", *(str+i)); //Output result: a-b-c
	}
    char name[9] = "cxx"; //End with "\ 0" in memory, and the value of 0ASCII code is 0
    char name1[9] = {'c,'x','x','\0'};
    char name2[9] = {'c','x','x',0};
    // When the number of array elements is greater than the stored character content, the default value of the uninitialized part is 0, so the following can also be regarded as a string
    char name3[9] = {'c','x','x'};

String output:

If a string is stored in the character array, Then the input and output of character array will become simple and convenient.
You don't have to use circular statements to input and output each character one by one
 have access to printf Function sum scanf The function outputs and inputs a string in a character array at one time
 The format string used is“%s",Indicates that the input and output is a string

The essence of outputting% s is to get the elements in the array one by one according to the address of the passed in name, and then output them until they meet the '\ 0' position

	char name[]="chenc\0hen";
	printf("%s\n",name); //Output result: chenc
 	//For a string array, if initialization assignment is not performed, the array length must be specified
	char name[10];
	scanf("%s",name); //Enter a string of characters
	
//name can store a string of up to 9 characters, and the position of the last character should be left for the end of the string to mark '\ 0'
//When inputting a string with scanf function, the string cannot contain spaces, otherwise spaces will be used as the end of the string;

String length calculation:

sizeof keyword:

Because the string is stored character by character in memory, and one character occupies one byte, the length of the end character of the string is also the number of bytes of the memory unit occupied.

    char name[] = "it666";
    int size = sizeof(name);// Contains \ 0
    printf("size = %d\n", size); //Output result: 6

strlen function:

Measure the actual length of the string (excluding the string end flag '\ 0') and return the value as a function.

  char name[] = "it666";
  size_t len = strlen(name2);
  printf("len = %lu\n", len); //Output result: 5

Statistics with "\ 0" as string end condition

/**
 *  Custom method to calculate the length of string
 *  @param name String to calculate
 *  @return Does not contain the length of \ 0
 */
int myStrlen2(char str[])
{
    //    1. Define the length of the variable save string
    int length = 0;
    while (str[length] != '\0')
    {
        length++;//1 2 3 4
    }
    return length;
}
/**
 *  Custom method to calculate the length of string
 *  @param name  String to calculate
 *  @param count Total length of string
 *  @return Does not contain the length of \ 0
 */
int myStrlen(char str[], int count)
{
//    1. Define the length of the variable save string
    int length = 0;
//    2. Get all characters in the string through traversal and compare them one by one
    for (int i = 0; i < count; i++) {
//        3. Judge whether it is the end of the string
        if (str[i] == '\0') {
            return length;
        }
        length++;
    }
    return length;
}

String concatenation function: strcat

Format: strcat (character array name 1, character array name 2)
Function: connect the string in character array 2 to the back of the string in character array 1, and delete the string flag "\ 0" after string 1. The return value of this function is the first address of character array 1.

char oldStr[100] = "welcome to";
char newStr[20] = " lnj";
strcat(oldStr, newStr);
puts(oldStr); //Output: welcome to lnj“

This program connects the character array of initialization assignment with the string of dynamic assignment.
It should be noted that the character array 1 should be defined with sufficient length, otherwise it cannot load all the connected strings.

String copy function: strcpy

Format: strcpy (character array name 1, character array name 2)
Function: copy the string in character array 2 to character array 1. The end of string flag "\ 0" is also copied. The character number name 2 can also be a string constant. This is equivalent to assigning a string to a character array.

char oldStr[100] = "welcome to";
char newStr[50] = " lnj";
strcpy(oldStr, newStr);
puts(oldStr); // Output result: lnj / / the original data will be overwritten

This function requires that the character array 1 should have sufficient length, otherwise it cannot load all the copied strings.

String comparison function: strcmp

Format: StrCmp (character array name 1, character array name 2)
Function: compare the strings in two arrays in ASCII code order, and return the comparison result by the return value of the function.
String 1 = string 2, return value = 0;
String 1 > string 2, return value > 0;
String 1 < string 2, return value < 0.

char oldStr[100] = "0";
char newStr[50] = "1";
printf("%d", strcmp(oldStr, newStr)); //Output result: - 1
char oldStr[100] = "1";
char newStr[50] = "1";
printf("%d", strcmp(oldStr, newStr));  //Output result: 0
char oldStr[100] = "1";
char newStr[50] = "0";
printf("%d", strcmp(oldStr, newStr)); //Output result: 1

Keywords: data structure pointer string

Added by Code_guy on Sun, 30 Jan 2022 06:28:09 +0200