为什么编译器会给我一个“不兼容的指针类型”警告?

时间:2017-01-15 08:02:29

标签: c pointers heap cs50

我正在阅读Greg Perry和Dean Miller撰写的C Programming Absolute Beginner's Guide一书

在第27章的一个名为“将数据放入结构变量”的子主题中,提供了以下代码。

当我尝试运行代码时,我遇到了很多错误。第一个是

27ex2.c:23:14: warning: incompatible pointer types assigning to
      'struct bookinfo *' from 'struct bookInfo *'
      [-Wincompatible-pointer-types]
                books[ctr] = (struct bookInfo*)malloc(sizeof(struct bookInfo));

这是代码。

#include "bookinfo.h"
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ctr;
    struct bookinfo * books[3]; // Array of three structure variables


    // Get the information about each book from the user

    for (ctr = 0; ctr < 3; ctr++)
    {
        books[ctr] = (struct bookInfo*)malloc(sizeof(struct bookInfo));

        printf("What is the name of the book #%d?\n", (ctr+1));
        gets(books[ctr]->title);
        puts("Who is the author? ");
        gets(books[ctr]->author);
        puts("How much did the book cost? ");
        scanf(" $%f", &books[ctr]->price);
        puts("How many pages in the book? ");
        scanf(" %d", &books[ctr]->pages);
        getchar(); //Clears newline input to keep things clean for
        // next round
    }

    // Print a header line and then loop through and print the info

    printf("\n\nHere is the collection of books:\n");
    for (ctr = 0; ctr < 3; ctr++)
    {
        printf("#%d: %s by %s", (ctr+1), books[ctr]->title, books[ctr]->author );
        printf("\nIt is %d pages and costs $%.2f", books[ctr]->pages, books[ctr]->price);
        printf("\n\n");
    }
    return(0);
}

有人能告诉我为什么会收到此错误吗?

以下是头文件以防万一。

// This header file defines a structure for information about a book

struct bookInfo {
    char title[40];
    char author[25];
    float price;
    int pages;
};

提前感谢您的帮助。我正在学习再次使用stackoverflow,所以请告诉我,如果我的帖子没有遵循社区准则,我会相应地调整它。

1 个答案:

答案 0 :(得分:7)

因为编译器区分大小写,bookinfobookInfo是不同的东西。