【发布时间】:2018-07-06 17:46:08
【问题描述】:
这是我用以下成员定义的结构:
struct id{
char name[32];
int age;
float iq;
};
这是其中一种功能中的打印语句:
printf("Enter your age: ");
scanf("%d",p->age);
printf("Enter your iq: ");
scanf("%f",p->iq);
问题是,代码编译时带有 2 个警告:
format '%d' expects argument of type 'int *', but argument 2 has type
'int'.
format '%f' expects argument of type 'float *', but argument 2 has type
'double'.
Build/Run 的输出,返回:
segmentation failed(core dumped).
任何帮助将不胜感激。
也有人可以远程指导我吗?成为 C 编程的天才? :p
这是我的程序的完整源代码,无法理解为什么它不能工作,我想要的方式。我找到了解决方法,但我想了解警告消息背后的概念。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*declaring struct as global item*/
struct id{
char name[32];
int age;
float iq;
};
/*prototyping*/
struct id *fAllocate(void);
void fFetch(struct id *p);
void fShow(struct id *p);
int main()
{
struct id *author; //declaring the var of_type struct id
/*allocate struct - fAllocate()_function*/
author = fAllocate();
/*fetch structure/populate - fFetch()_function*/
fFetch(author);
/*show struct - fShow()_function*/
fShow(author);
return 0;
}
/*fAllocate()_function*/
struct id *fAllocate(void){
struct id *p;
p = (struct id *)malloc(sizeof(struct id));
if(p == NULL)
{
printf("Memory Unavailable!");
exit(1);
}
else
{
return(p);
}
return;
}
/*fFetch()_fucntion*/
void fFetch(struct id *p){
//declaring var to store scanf values
/*
char *n;
int i;
float f;
*/
printf("Enter your name: ");
scanf("%s",p->name //&n);
//strcpy(p->name,n);
printf("Enter your age: ");
scanf("%d",p->age //&i);
//p->age = i;
printf("Enter your iq: ");
scanf("%f",p->iq //&f);
//p->iq = f;
return;
}
/*fShow()_function*/
void fShow(struct id *p){
printf("Author %s is %d years old!\n",
p->name,
p->age);
printf("%s has an iq of %.2f!\n",
p->name,
p->iq);
return;
}
【问题讨论】:
-
您可能想查看
scanf()的文档。 -
您忘记获取相关对象的地址。
-
@alk 谢谢你所说的有效,但是我必须使用 &(p->age),指针周围的括号。谢谢!!
标签: c function pointers structure