gpt4 book ai didi

c++ - 为什么指针不递增

转载 作者:太空狗 更新时间:2023-10-29 23:28:35 27 4
gpt4 key购买 nike

作为 c++ 的新手,我一直在练习问题。我写的一个程序包括结构和数组的使用:

#include <iostream>
using namespace std;

int main (void){
struct CandyBar{
char brandName[200];
float weight;
int calories;
};

CandyBar snacks[3] = {
{"Cadbury's Flake",23.5,49},
{"Cadbury's Wispa",49.3,29},
{"Cadbury's Picnic",57.8,49},
};

for(int i=0;i<3;i++){
cout << "Brand Name: " << snacks[i].brandName << endl;
cout << "Weight: " << snacks[i].weight << endl;
cout << "Calories: " << snacks[i].calories << endl;
snacks++;
}

cin.get();
return 0;
}

上面的程序因为“snacks++”而失败,但我不明白为什么。据我了解,数组由指针(“snacks”)和对象([])两部分组成,所以“snacks++”不应该在我递增指针时工作吗?

谢谢丹

最佳答案

只需删除snacks++;
您已经在使用变量 i 作为数组中的索引。

如果你想使用指针算法:
A。您应该定义一个指向数组开头的指针并使用它而不是使用数组。
b.访问数据时,您应该使用指针而不是索引为 i 的数组。

struct CandyBar* ptr = snacks;
for(int i=0;i<3;i++){
cout << "Brand Name: " << ptr->brandName << endl;
cout << "Weight: " << ptr->weight << endl;
cout << "Calories: " << ptr->calories << endl;
ptr++;
}

关于c++ - 为什么指针不递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10061604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com