700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > c语言结构体内嵌结构体指针_C语言中的结构指针

c语言结构体内嵌结构体指针_C语言中的结构指针

时间:2023-12-19 09:14:37

相关推荐

c语言结构体内嵌结构体指针_C语言中的结构指针

c语言结构体内嵌结构体指针

Prerequisite:

先决条件:

Structures in C programming language.

C编程语言中的结构。

Dynamic Memory allocation functions in C.

C中的动态内存分配功能。

Example:In this tutorial, we will use a structure for “student”, structure members will be "name" (string type), "age" (integer type), "roll number" (integer type).

示例:在本教程中,我们将为“学生”使用结构,结构成员将为“名称”(字符串类型),“年龄”(整数类型),“卷数”(整数类型)。

结构声明 (Structure declaration)

struct student{char name[50];int age;int rollno;};

Here,

这里,

struct is the keyword to define a structure.

struct是定义结构的关键字。

student is the name of the structure.

学生是结构的名称。

name is the first structure member to store age with maximum of 50 characters, age is second structure member to store age of the student, and rollno is the third structure member to store rol number of the student.

name是存储年龄最多的50个字符的第一个结构成员, age是存储学生年龄的第二个结构成员, rollno是存储学生的编号的第三个结构成员。

指向结构声明的指针 (Pointer to structure declaration)

struct student *ptr;

将内存分配给结构指针 (Allocating memory to the pointer to structure)

ptr = (struct student*)malloc(sizeof(struct student));

The statement will declare memory for one student’s record at run time. Read more about the dynamic memory allocation in C programming language.

该语句将在运行时声明对一个学生的记录的记忆。 阅读有关C编程语言中动态内存分配的更多信息。

使用指针访问结构成员 (Accessing structure members using pointer)

Thearrow operator(->) is used to access the members of the structure usingpointer to structure. For example, we want to access member name, and ptr is thepointer to structure. The statement to access name will be ptr->name.

箭头运算符( -> )用于使用指向结构的指针访问结构的成员。 例如,我们要访问成员名称 ,而ptr是指向structure的指针。 访问名称的语句将是ptr-> name 。

指向结构的C程序 (C program for pointer to structure)

#include <stdio.h>//structure definitionstruct student{char name[50];int age;int rollno;};//main functionint main(){//pointer to structure declarationstruct student *ptr;//allocating memory at run time ptr = (struct student*)malloc(sizeof(struct student));//check memory availabilityif( ptr == NULL){printf("Unable to allocate memory!!!\n");exit(0);}//reading values of the structureprintf("Enter student details...\n");printf("Name? ");scanf("%[^\n]", ptr->name); //reads string with spacesprintf("Age? ");scanf("%d", &ptr->age);printf("Roll number? ");scanf("%d", &ptr->rollno);//printing the detailsprintf("\nEntered details are...\n");printf("Name: %s\n", ptr->name);printf("Age: %d\n", ptr->age);printf("Roll number: %d\n", ptr->rollno);//freeing dynamically allocated memoryfree(ptr);return 0;}

Output

输出量

Enter student details...Name? Amit shuklaAge? 21Roll number? 100Entered details are...Name: Amit shuklaAge: 21Roll number: 100

翻译自: /c/pointer-to-structure.aspx

c语言结构体内嵌结构体指针

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。