格式' _'期望类型' __'但是参数2的类型为' __'。 C编程,我是初学者

时间:2018-01-27 15:40:01

标签: c function pointers structure

这是我用以下成员定义的结构:

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-Programming的天才? :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;
}

1 个答案:

答案 0 :(得分:1)

scanf()需要能够存储它扫描的数据。所以它需要地址,如下所示:

scanf("%d", &p->age);

scanf("%f", &p->iq);

POSIX documentation is here.