我一直在讨论关于双指针的错误,并且我在引用和指针之间不断变换,但只是不断出错。我不需要地址,我只需要将地址传递给函数。
#include <iostream>
#include <stdlib.h> //need for rand()
using namespace std;
//GLOBAL CONSTANTS
#define ARRAYSIZE 100
#define RANDOMNUMBERS 6
//Function Declarations
void fillUpArray(int *[]);
void freqOfData(int *[], int *[]);
void outPutFreq(int *[]);
//Main function
int main()
{
//Build arrays and make them so they are the right size
int dataArray[ARRAYSIZE] = {};
int freqArray[RANDOMNUMBERS] = {}; //frequencies need to be 0 to start
int* dataPointer = &dataArray;
int* freqPointer = &freqArray;
//fill up the big data array
fillUpArray(dataPointer);
//find the frequencies and put them in the frequency array
freqOfData(dataPointer, freqPointer);
//send the frequencies to be outputted
outPutFreq(freqPointer);
//end the program
return 0;
}
//User Defined Functions
void fillUpArray(int *array[])
{
for(int i = 0; i < ARRAYSIZE; i++)
{
*array[i] = rand() % 6 + 1;
}
}
void freqOfData(int *data[], int *frequency[])
{
//walk through the entire array
for(int i = 0; i < ARRAYSIZE; i++)
{
//find out what value is in this spot and add one to that frequency
//a switch(case) is better than if statements but if you don't know it don't worry about it
if(*data[i] == 1)
{
*frequency[0] = *frequency[0] + 1;
}
else if(*data[i] == 2)
{
*frequency[1] = *frequency[1] + 1;
}
else if(*data[i] == 3)
{
*frequency[2] = *frequency[2] + 1;
}
else if(*data[i] == 4)
{
*frequency[3] = *frequency[3] + 1;
}
else if(*data[i] == 5)
{
*frequency[4] = *frequency[4] + 1;
}
else if(*data[i] == 6)
{
*frequency[5] = *frequency[5] + 1;
}
else
{
//never should go here <-- means there is mistake in our code
}
}
}
void outPutFreq(int *output)
{
cout << "The Frequency of 1 in the Array is " << output[0] << endl;
cout << "The Frequency of 2 in the Array is " << output[1] << endl;
cout << "The Frequency of 3 in the Array is " << output[2] << endl;
cout << "The Frequency of 4 in the Array is " << output[3] << endl;
cout << "The Frequency of 5 in the Array is " << output[4] << endl;
cout << "The Frequency of 6 in the Array is " << output[5] << endl;
}
编辑:我为#34;非主题&#34;而道歉。这个函数假设有一个main(),它有两个调用3个方法的数组。这些方法使用随机数据(1到6)填充其中一个数组。第二种方法计算出数字1 - 6的出现频率。最后一种方法将采用这个频率数组并以格式输出它#34;数组中#的频率为##&#34;
答案 0 :(得分:1)
您的代码无法编译。这里的问题是:
int*
是指向int的指针,int*
也是指向int
数组的指针。 int a[...];
即可获取数组a
的地址。不得使用&
。但如果你真的喜欢这种表示法,你可以写&a[0]
。int *a[]
指的是二维数组int*
或int[]
,而不是两者一起。在被调用函数中作为数组,没有*
示例:
void fillUpArray(int array[])
{
for (int i = 0; i < ARRAYSIZE; i++)
{
array[i] = rand() % 6 + 1;
}
}
如果您实施所有这些更正,程序编译甚至可以正常工作!
现在除此之外,与你的问题没有直接关系:
const
个变量。现在应该避免#define
。