Answer the question
In order to leave comments, you need to log in
Identifier is not defined. How to solve this problem?
There is a part of the code, it is required to write a function. I wrote the function, but the compiler swears, I just can’t figure out what’s wrong.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int* my_slightly_dumb_reallocation(int* source, unsigned int n_old, unsigned int n_new);
int main() {
unsigned int n, i;
cin >> n;
int *a = my_slightly_dumb_reallocation(NULL, 0, n / 2);
for (i = 0; i < n / 2; i++)
cin >> a[i];
a = my_slightly_dumb_reallocation(a, n / 2, n);
for (; i < n; i++)
cin >> a[i];
int sum = 0;
for (i = 0; i < n; i++)
sum += a[i];
cout << sum << endl;
a = my_slightly_dumb_reallocation(a, n, n / 2);
a = my_slightly_dumb_reallocation(a, n / 2, 0);
a = my_slightly_dumb_reallocation(a, 0, 0);
return 0;
}
int* my_slightly_dumb_reallocation(int* source, unsigned int n_old, unsigned int n_new) {
if (source == NULL) {
int* array = new int[n_new];
}
else {
int* array = new int[n_new];
for (int i = 0; i < n_old && i < n_new; i++) {
array[i] = source[i];
}
delete[] source;
source = nullptr;
}
return array;
}
Answer the question
In order to leave comments, you need to log in
int* my_slightly_dumb_reallocation(int* source, unsigned int n_old, unsigned int n_new) { if (source == NULL) { int* array = new int[n_new]; } ... return array; }
the compiler complains
array
is defined in a block but return array
is outside of that block. You either put return into the block, or take it int *array = new int[n_new];
out of the block to the same level as return array
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question