So I'm very new to pointers and pointer syntax, and I've just written this function but have about 5-6 build errors and after looking at the code for a while, I'm still unsure on how to fix them or why they are errors. I'm new to pointers and memory so that is why I am unsure regarding how to fix these bugs and why they are wrong. Thanks for your help it is appreciated it!
int makeFrequency (int data[], int dSize, int *minDataValue, int *maxDataValue)
{
findMinAndMax(data, dSize, minDataValue, maxDataValue);
int fSize = *minDataValue + *maxDataValue; // invalid operands of types 'int' and 'int*' to binary 'operator+' error?
int frequency = new int [fSize]; //invalid conversion error?
if (frequency == NULL)
{
return NULL;
}
for (int i = 0; i <= fSize; i++)
{
frequency[i] = 0; // invalid types 'int[int]' for array subscript error?
}
for (int i = 0; i <= dSize; i++)
{
int j = data[i] - (*minDataValue)+1; // invalid operands of types 'int' and 'int*' to binary 'operator-' error?
frequency[j] = frequency[j] + 1; // invalid types 'int[int]' for array subscript error?
}
return frequency;
}
int main() {
int dSize;
int *ArrayOfInts;
cout << "How many data values? ";
cin >> dSize;
ArrayOfInts = new int [dSize];
getData(dSize, ArrayOfInts);
int *frequency, min, max;
frequency = makeFrequency (ArrayOfInts, dSize, &min, &max); // invalid conversion error?
if (frequency == NULL) return -1;
makeHistogram(frequency, min, max);
delete [] frequency;
return 0;
}
int frequency = new int [fSize]; //invalid conversion error?
new
returns a pointer to the heap-allocated object. When you allocate X
, new
return an X *
.
new X[n]
allocates n
instances of X
and returns a pointer to the first instance of X.
(In all cases, new
also invokes the allocated objects' constructors, but this is an irrelevant point here).
new int [fSize];
Therefore, this expression returns an int *
.
int frequency
frequency
is, obviously an int
.
int frequency = new int [fSize];
Putting all of the above together, here you are attempting to assign an int *
to an int
. That's your conversion error. frequency
should be declared as an int *
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.