【C language】-- . and -> usage difference

In the C language, a structure (struct) is a user-defined data type that can contain multiple data members of different types. The following is the difference between "." and "->":

1. The "." operator is used to access the members of the structure variable, which means the member variable or member function of the structure variable. For example:

struct Student {
   char name[10]; 
   int age; 
}; 
struct Student s;
s.age = 20; 

Indicates accessing the age member variable in the structure variable s and setting its value to 20.


2.  The "->" operator is used to access members in the structure pointer, which means the member variable or member function of the structure variable pointed to by the structure pointer variable. For example:

struct Student { 
    char name[20]; 
    int age;
};
struct Student *p = &s;
p->age = 20;

Indicates accessing the age member variable in the structure variable s pointed to by the structure pointer variable p, and setting its value to 20. It should be noted that when using the "->" operator, the pointer variable must first point to a valid structure variable, otherwise it will cause a program error.
 

由于a->b The meaning is  (*a).b , so they are different, but  -> can be used  * and  . implemented.

Struct variables use . to access the members of the structure as follows:

#include<stdio.h>
#include <malloc.h>
struct stu{
	int  age;
	stu* next;
};
int main(){
	stu s1;
    s1.age =20;
	
	return 0;
}

A pointer to a structure uses -> to access the members of the structure it points to as follows:

#include<stdio.h>
#include <malloc.h>
struct stu{
	int  age;
	stu* next;
};
int main(){
	stu *phead = (stu*)malloc(sizeof(stu)); 
    phead->age=20;
	phead->next = NULL;
	stu* p = phead;
	
	return 0;
}

The summary is as follows: 
1. A->a means that A is a pointer to a structure.
2. Aa means that A is a structure.
3. A->a is equivalent to (*A).a.

4. For AB, A is an object or a structure.

5. For A->B, A is a pointer, -> is member extraction, A->B is to extract member B in A, and A can only be a pointer to a class, structure, or union.

6. (*a).b is equivalent to a->b. "." is generally read as "of"; "->" is generally read as "of the structure pointed to". That is to say, in the structure, operator -> is the combination of operator * and operator .
7. "->" points to the first address of the structure or object. "." points to a structure or an object.

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/131316235