我收到一个错误:
error: request for member ‘clsf_ptr’ in something not a structure or union
来自这个 C 程序:
#include<stdio.h>
#define M 3
struct class_stud
{
char name[16];
char subject[16];
int roll_num;
}
struct node
{
int n;
struct branch *p[M];
struct class_stud cls[M-1];
}*root=NULL;
main()
{
int clsf_cnt;
struct class_stud clsf, *clsf_ptr;
clsf_ptr = &clsf;
clsf_cnt = 0;
root = malloc(sizeof (struct node));
printf("enter source address \n");
scanf("%s",&root.clsf_ptr[clsf_cnt]->name);
printf("%s",root.clsf_ptr[clsf_cnt]->name);
printf("enter key\n");
scanf("%d",&root.clsf_ptr[clsf_cnt]->key);
printf("%d",root.clsf_ptr[clsf_cnt] -> key);
clsf_cnt++;
}
错误是什么意思?
最佳答案
此代码中存在许多问题。让我们逐行浏览它:
#include<stdio.h>
#define M 3
struct class_stud
{
char name[16];
char subject[16];
int roll_num;
}
第一个问题;您需要在上面的结构定义之后结束 ;
。此外,有趣的是,您没有为 name
和 subject
数组的长度定义预处理器宏,但此时这是一个小问题。
struct node
{
int n;
struct branch *p[M];
struct class_stud cls[M-1];
}*root=NULL;
struct branch
的定义在哪里? p
在结构定义中应该表示什么?为什么 cls
中的元素比 p
少一个?
main()
从 C99 开始,您无法摆脱 main
的隐式类型;它必须显式键入以返回 int
。而且,由于您没有弄乱任何命令行参数,因此最好将参数列表显式设置为 void
,如下所示:
int main(void)
{
int clsf_cnt;
struct class_stud clsf, *clsf_ptr;
clsf_ptr = &clsf;
上面的操作有什么作用?
clsf_cnt = 0;
root = malloc(sizeof (struct node));
这很好,但是编写此代码的首选方式是
root = malloc(sizeof *root);
这样你就可以确保根据 root
的类型分配正确的内存量。
printf("enter source address \n");
scanf("%s",&root.clsf_ptr[clsf_cnt]->name);
确认。一行中的多个问题。
首先,clsf_ptr
不是 struct node
的成员。您可能打算访问 cls
。其次,由于 root
是指向结构的指针,您需要使用 ->
运算符来访问其成员(或显式取消引用 root
然后使用 .
)。第三,cls[clsf_cnt]
不是指针类型,因此您可以使用 .
运算符访问 name
.最后,由于 name
是一个数组类型,它会在传递给 scanf
之前隐式转换为指针类型,所以 &
不是'没必要。
为了避免缓冲区溢出,您应该在 %s
转换说明符中放置最大字段宽度,或者使用 fgets()
而不是 scanf ()
。
坚持scanf()
,那一行应该写成
scanf("%15s", root->cls[clsf_cnt].name);
我在转换说明符中使用 15 而不是 16,以便我们为 0 终止符保留一个字符。
使用 fgets(),将写入该行
fgets(root->cls[clsf_cnt].name, sizeof root->cls[clsf_cnt].name, stdin);
printf("%s",root.clsf_ptr[clsf_cnt]->name);
同样,您正在尝试访问不是 root
成员的内容,并且您的访问操作符是倒过来的:
printf ("%s", root->cls[clsf_cnt].name);
printf("enter key\n");
scanf("%d",&root.clsf_ptr[clsf_cnt]->key);
printf("%d",root.clsf_ptr[clsf_cnt] -> key);
struct class_stud
没有名为key
的成员;也许你的意思是 roll_num
?
scanf("%d", &root->cls[clsf_cnt].roll_num);
printf("%d", root->cls[clsf_cnt].roll_num);
clsf_cnt++;
}
看起来您发布了一些不完整的内容;确保您向我们展示的是您尝试构建的相同代码。
关于C、如何从另一个结构访问一个结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828812/