0
ここでC++ newbieと私は理解できない問題にぶつかりました。関数の問題でのC++配列の割り当て
私が期待される正しい結果を得るの下にIコードを実行する:
#include <iostream>
#include <math.h>
void factorize(int *factors, int number)
{
// declare vars
int index = 0;
// find factors of number
for (int x = 1; x <= number; ++x) {
// if x is a factor of number, save it to array
if (number % x == 0) {
std::cout << " Index: " << index << ", F: " << x << "\n";
index++;
}
}
}
int main()
{
//declare vars
int triangle = 0;
int factors[] = {};
//loop through all numbers
for (int x = 1; x <= 5; ++x) {
// calculate triangle value
std::cout << "initial triangle value: " << triangle << ", ";
triangle = triangle + x;
std::cout << "x value: " << x << " , new triangle value: " << triangle << "\n\n";
// find factors of triangle number
factorize(factors, triangle);
std::cout<<"\n";
}
return 0;
}
正しい結果:私はライン因子[インデックス] = xを追加するとき
initial triangle value: 0, x value: 1 , new triangle value: 1 Index: 0, F: 1 initial triangle value: 1, x value: 2 , new triangle value: 3 Index: 0, F: 1 Index: 1, F: 3 initial triangle value: 3, x value: 3 , new triangle value: 6 Index: 0, F: 1 Index: 1, F: 2 Index: 2, F: 3 Index: 3, F: 6 initial triangle value: 6, x value: 4 , new triangle value: 10 Index: 0, F: 1 Index: 1, F: 2 Index: 2, F: 5 Index: 3, F: 10 initial triangle value: 10, x value: 5 , new triangle value: 15 Index: 0, F: 1 Index: 1, F: 3 Index: 2, F: 5 Index: 3, F: 15
をしかし、から
因数分解関数、私は奇妙な結果を取得します。何らかの理由で、
メイン三角形
の値が変更されます。 (三角形値がどのようになる気づく:、、、その後何らかの理由にジャンプして戻る): #include <iostream>
#include <math.h>
void factorize(int *factors, int number)
{
// declare vars
int index = 0;
// find factors of number
for (int x = 1; x <= number; ++x) {
// if x is a factor of number, save it to array
if (number % x == 0) {
std::cout << " Index: " << index << ", F: " << x << "\n";
factors[index] = x;
index++;
}
}
}
int main()
{
//declare vars
int triangle = 0;
int factors[] = {};
//loop through all numbers
for (int x = 1; x <= 5; ++x) {
// calculate triangle value
std::cout << "initial triangle value: " << triangle << ", ";
triangle = triangle + x;
std::cout << "x value: " << x << " , new triangle value: " << triangle << "\n\n";
// find factors of triangle number
factorize(factors, triangle);
std::cout<<"\n";
}
return 0;
}
予期しない結果
initial triangle value: 0, x value: 1 , new triangle value: 1
Index: 0, F: 1
initial triangle value: 1, x value: 2 , new triangle value: 3
Index: 0, F: 1
Index: 1, F: 3
initial triangle value: 3, x value: 3 , new triangle value: 6
Index: 0, F: 1
Index: 1, F: 2
Index: 2, F: 3
Index: 3, F: 6
initial triangle value: 2, x value: 4 , new triangle value: 6
Index: 0, F: 1
Index: 1, F: 2
Index: 2, F: 3
Index: 3, F: 6
initial triangle value: 2, x value: 5 , new triangle value: 7
Index: 0, F: 1
Index: 1, F: 7
私は何が欠けていますか?
int factors[] = {};
0のサイズの配列は、C++ではサポートされていません。しかし、多くのコンパイラは拡張機能として提供しています。 –
@FrançoisAndrieuxTrueですが、コンパイラはこれを拡張子として使用できますか?コンパイラやそれが与える警告を知らなければ、より具体的に言うのは不可能です。 –