如何使用C语言访问结构指针?
结构指针保存整个结构的地址。
这些主要用于创建复杂的数据结构,例如链表,树,图等。
可以使用称为箭头运算符(->)的特殊运算符来访问结构的成员。
宣言
以下是指向结构的指针的声明-
struct tagname *ptr;
例如,struct学生* s;
存取中
您可以使用以下命令访问结构的指针-
Ptr-> membername;
例如,s-> sno,s-> sname,s-> marks;
示例
以下是C程序访问指向结构的指针-
#include<stdio.h>输出结果struct classroom{
int students[7];
};
int main(){
struct classroom clr = {2, 3, 5, 7, 11, 13};
int *ptr;
ptr = (int *)&clr;
printf("%d",*(ptr + 4));
return 0;
}
执行以上程序后,将产生以下结果-
11
解释
这里,指针变量ptr保存对象clr的第一值2的地址。然后,将指针变量的地址加4,最后显示该值。
例如,
*(ptr + 0) = 2*(ptr + 1) = 3
*(ptr + 2) = 5
*(ptr + 3) = 7
*(ptr + 4) = 11
*(ptr + 5) = 13
考虑另一个简单的示例,以了解有关结构的指针-
示例
struct student{输出结果int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks :");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are\n");
printf ("Number = %d\n", st ->sno);
printf ("name = %s\n", st->sname);
printf ("marks =%f", st->marks);
getch ( );
}
执行以上程序后,将产生以下结果-
enter sno, sname, marks :1 bhanu 69details of the student are
Number = 1
name = bhanu
marks =69.000000
以上是 如何使用C语言访问结构指针? 的全部内容, 来源链接: utcz.com/z/333653.html