不兼容的类型 - 是因为数组已经是一个指针了? [英] Incompatible types - is it because an array is already a pointer?

查看:164
本文介绍了不兼容的类型 - 是因为数组已经是一个指针了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我创建一个基于书籍结构的对象,并且它拥有多个书籍我设置是一个数组(被定义/启动的对象)。但是,每当我去测试我的指针知识(实践帮助),并试图做一个指针指向创建的对象,它给我的错误:

In the below code I create an object based off of the books structure, and to have it hold multiple "books" I set is an array (the object that is defined/initiated, that is). However, whenever I went to test my knowledge of pointers (the practice helps) and attempted to make a pointer that points to the created object, it gives me the error:

C:\Users\Justin\Desktop\Project\wassuip\main.cpp | 18 |错误:将书籍分配给books * [4]时不兼容的类型| *

C:\Users\Justin\Desktop\Project\wassuip\main.cpp|18|error: incompatible types in assignment of 'books' to 'books* [4]'|*

我可以问,这是因为对象book_arr []已经被认为是一个指针,因为它是一个数组?感谢(新到C ++,只想验证)。

May I ask, is this because the object book_arr[] is already considered a pointer as it's an array? Thanks (new to C++ and just want to verify).

#include <iostream>
#include <vector>
#include <sstream>

#define NUM 4

using namespace std;

struct books {
    float price;
    string name;
    int rating;
} book_arr[NUM];

int main()
{
    books *ptr[NUM];
    ptr = &book_arr[NUM];

    string str;

    for(int i = 0; i < NUM; i++){
        cout << "Enter book name: " << endl;
        cin >> ptr[i]->name;
        cout << "Enter book price: " << endl;
        cin >> str;
        stringstream(str) << ptr[i]->price;
        cout << "Enter book rating: " << endl;
        cin >> str;
        stringstream(str) << ptr[i]->rating;
    }

    return 0;
}

* 答案后的新代码(无错误)*

#include <iostream>
#include <vector>
#include <sstream>

#define NUM 4

using namespace std;

/* structures */
struct books {
    float price;
    string name;
    int rating;
} book[NUM];

/* prototypes */
void printbooks(books book[NUM]);

int main()
{
    string str;

    books *ptr = book;

    for(int i = 0; i < NUM; i++){
        cout << "Enter book name: " << endl;
        cin >> ptr[i].name;
        cout << "Enter book price: " << endl;
        cin >> str;
        stringstream(str) << ptr[i].price;
        cout << "Enter book rating: " << endl;
        cin >> str;
        stringstream(str) << ptr[i].rating;
    }

    return 0;
}

void printbooks(books book[NUM]){
    for(int i = 0; i < NUM; i++){
        cout << "Title: \t" << book[i].name << endl;
        cout << "Price: \t$" << book[i].price << endl;
        cout << "Racing: \t" << book[i].rating << endl;
    }
}


推荐答案

img src =http://i.imgur.com/Zwhdn.gifalt =数组不是指针>

请参阅如何在C ++中使用数组?详细信息。

这篇关于不兼容的类型 - 是因为数组已经是一个指针了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆