int scores[1][3] = 100;
doesn't work.The memory needed to store the array named data is allocated and deallocated based on scope. But the problem is that the memory is deallocated, not that the variable goes out of scope. We'll look at three ways of fixing the error below. All three corrections use a variable named data and it does go out of scope when the get_data function ends, but the memory in the solutions is not deallocated when the function ends.
int* get_data() { int data[100]; // fill the data array return data; }
new
operator. The local variable data goes out of scope when the function ends but the memory allocated by new
is not deallocated.
int* get_data() { static int data[100]; // fill the data array return data; } |
int* get_data(int* data) { // fill the data array return data; } |
int* get_data() { int* data = new int[100]; // fill the data array return data; } |
.length
.
See sg02_answers, question 28.
The Problem | The Solution |
---|---|
void f(foo* data, int x, int y) { . . . } |
foo temp = data[x]; data[x] = data[y]; data[y] = temp; |
The type of the array is foo, so the type of the temporary variable, temp in this example, must also be foo - int will not work. The name of the temporary variable is not significant.
void copy(char* destination, char* source, int size) { for (int i = 0; i < size; i++) destination[i] = source[i]; }
//double average(double[] scores, int size) double average(double* scores, int size) { double sum = 0; for (int i = 0; i < size; i++) sum += scores[i]; return sum / size; }
Some issues to consider:
temp = scores[i]; sum = sum + temp;but doing so adds no value to the program