如何正确地将带有指针的数组传递给函数

How do you correctly pass arrays with pointers to a function?

本文关键字:数组 函数 指针 正确地      更新时间:2023-10-16

我必须动态分配一个数组,并将其传递给一个函数,以计算加权骰子滚动的几率。每当我运行代码时,函数都不记得添加到数组中的值,并返回随机值,那么我将*weight传递到roll函数的方式有什么问题?我在中添加权重后添加了print语句,并且权重输入得很好,直到它通过指针传递给函数。

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int roll (int sides, double *weight) {
int total[sides + 1];
total[0] = 0;
for (int i = 1; i <= sides; i++) {
total[i] = total[i - 1] + weight[i]; 
}

int current = (rand() % total[sides + 1] - 1 + 1);
//cout << current << " ";
for (int i = 1; i <= sides; i++) { // 1 to weight 1,,,,, weight 1 to weight 
2
if (current <= total [i] && current > total[i - 1]) {
current = i;
}
}

return current;
}

应该检索滚动的随机数的函数。^

int main () {
int sides = 0;
int rolls = 0;
int answer = 0;
int currentRoll = 0;
bool done = false;
double* weight;
double totalWeight;
srand(time(NULL));
cout << "Dice Roll Menu: " << endl << "1. Specify an output file" << endl << 
"2. Enter sides and weight for a die" << endl << "3. Simulate a specified 
number of rolls of the weighted die" << endl << "4. Exit" << endl;
while (done != true) {
cout << endl << "Enter a number that corresponds to you choice: ";
cin >> answer;

while (answer == 2) { //SIDES
cout << "Please enter the number of sides on the die (must be 
greater than two): ";
cin >> sides;
if (sides < 2) {
cout << "Invalid input, try again." << endl;
}
else {
weight = new double[sides + 1];
for (int i = 0; i < sides + 1; i++) {
weight[i] = 0;
}
break;
}
}

while (answer == 2) {
totalWeight = 0;
for (int i = 1; i <= sides; i++) { //WEIGHT 
cout << "Enter a weight for side " << i << ": ";
cin >> weight[i];
cout << "TEST: " << weight[i] << endl;
totalWeight = weight[i] + totalWeight;
if (weight[i] < 0) {
cout << "Invalid input. Try again.";
totalWeight -= weight[i];
i--;
}
}
break;
}

确定边和权重并动态分配数组的循环。^

while (answer == 3) {
cout << "Enter the amount of rolls you would like to perform: ";
cin >> rolls;
if (rolls < 0) {
cout << "Invalid input. Try again.";
}
else {
else if (totalWeight == 0) {
cout << "Please enter weights of the dice first!" << endl;
answer = 1;
}
else {
done = true;
break;
}
}
}
//ACTUAL CODE HERE
for (int i = 1; i <= rolls; i++) { //CALCULATES
currentRoll = roll(sides, &weight[i]);
cout << currentRoll << " ";
}

}

也许注释中的许多误解都与简单地使用C++有关(但不使用std::containers(。

我的开箱即用的想法(或者说完全疯狂(是:之间真的没有冲突

  • "我必须能够使用‘动态分配的数组’完成这个程序,遗憾的是,我不允许使用向量

  • 然而,所有相关人员似乎都同意这个是一个C++类赋值。


因此,我们需要考虑一种动态创建数组的方法(我认为这部分很容易,不确定为什么(。我们想要一些编译时固定大小的东西。数组必须存在于动态内存中。(没有std容器。(

目标也被简单地表述为

我必须动态分配一个数组,并将其传递给一个函数计算。。。

我提出以下建议。(此代码编译并运行。(

#include <iostream>
using std::cout, std::flush, std::endl;
// Step 1 - wrap an array inside a class
class Array_t
{
const int  m_sz;
int64_t*   m_arr;
public:
Array_t()
: m_sz(128)
, m_arr (new int64_t[m_sz]) // allocate array in dynamic memory
{
// init for easy sum ... -------------v
for (int j=0; j<m_sz; j+=1) m_arr[j] = 1; // easy sum
}
~Array_t() = default;
int64_t sum() {
int64_t retVal = 0;
for (int i=0; i<m_sz; i+=1)
retVal += m_arr[i];  // direct access to the data!
return retVal;
}
};
// If your C++ 'Hello World' has no class ... why bother?
// Step 2 - auto var the above
class DUMY999_t
{
public:
DUMY999_t() = default;
~DUMY999_t() = default;
int operator()(int argc, char* argv[]) { return exec(argc, argv); }
private:
int exec(int , char** )
{
// here is the array wrapped in a class, an automatic var!
// the array is dynamically allocated in the class (see ctor)
Array_t  arr;  
// ctor provides the compile time constant
// Step 3 
// pass the array (in the class) to some function foo()
cout << "n  foo(arr) :" << foo(arr) << endl;
// Step 4 - can we solve the 'how pass' question?
// It should be obvious that foo is redundant ...
// the following is both more direct
// and object-oriented (a good thing)
// >>> put the function in the object that has the data <<<    
cout << "n  arr.sum() :" << arr.sum() << endl;
// invoke an object method which has
// direct access to the data!
return 0;
}
// why pass the data to the function? (c-style?)
int64_t foo(Array_t& arr)
{
return arr.sum();
}
// why not install the function into the object? (c++?)
}; // class DUMY999_t
int main(int argc, char* argv[]) { return DUMY999_t()(argc, argv); }

典型输出:

foo(arr) :128
arr.sum() :128