【发布时间】:2015-04-29 17:55:36
【问题描述】:
我正在尝试遍历大小未知的double 数组。
为什么以下不起作用?
for (unsigned int = 1; i < sizeof(anArray)/sizeof(double); i++) {
...
}
一切都编译得很好(g++ -Wall -Werror -std=c++11 app.cpp -o app),但程序根本没有进入循环。
全功能:
struct stock_data {
int sell_index;
int buy_index;
double profit;
};
stock_data max_profit(double price_array[]) {
int sell_index = -1, buy_index = -1,
min = 0;
double profit = 0.0;
for(int i = 1; i < size; i++) {
if(price_array[i] - price_array[min] > profit) {
sell_index = min;
buy_index = i;
profit = price_array[i] - price_array[min];
}
if(price_array[i] < price_array[min]) {
min = i;
}
}
return {sell_index, buy_index, profit};
}
int main() {
double yesterday[] = {0.1, 0.2, 0.3, 0.4};
stock_data data = max_profit(yesterday);
cout << data.profit << endl;
}
【问题讨论】:
-
sizeof(anArray)告诉你一个指针的大小,当它除以一个 double 的大小时,是 0 或 1。 -
我的水晶球说你将
anArray传递给了这个函数,它衰减为一个指针。希望我能看到足够多的代码来确定。 -
这个数组是在哪里声明的?如果它在其他块中,它可能不起作用。
-
没有足够的代码来确定任何事情。如果您将 anArray 声明为 double anArray[
] 并且 anArray 没有衰减为只是一个指针,那么该代码将起作用。 -
谈话很便宜。向我们展示代码。
标签: c++ arrays for-loop sizeof function-definition