I have two pointer arrays for example ptr1 and ptr2, a size of 10 for each, and init random variable for every element for both. I want to compute and init two elements of ptr1 and ptr2 for each element of another array called ptr3. But when I print ptr3 out. It is not changed at all.
here is my code:
void evaluateArr(int* ptr1, int* ptr2, double* ptr3, int n) {
// ptr3 = new double[10];
for (int i = 0; i < n; ++i) {
if (ptr1[i] > ptr2[i]) {
ptr3[i] = (double)(*(ptr1 + i) * 60 / 100);
ptr3[i] += (double)(ptr2[i] * 40 / 100);
} else {
ptr3[i] = (double)(*(ptr2 + i) * 60 / 100);
ptr3[i] += (double)(ptr1[i] * 40 / 100);
}
}
}
void printResult(double* ptr3) {
for (int i = 0; i < 10; ++i) {
printf("%d ", *(ptr3 + i));
}
}
int main() {
int ptr1[10], ptr2[10];
double ptr3[10];
// init for arr1 and arr2
for (int i = 0; i < 10; i++) {
ptr1[i] = (rand() % 100);
ptr2[i] = (rand() % 100);
}
// it prints out 0 0 0 0 0 0 0 0 0 0
evaluateArr(ptr1, ptr2, ptr3, 10);
printResult(ptr3);
}
%ffor double, not%d.*(ptr1 + i) * 60.0 / 100. That is, casting the final result todoubleis too late. Make one of the numbersdoubleinstead.ptr3[i] = (double)(*(ptr1 + i) * 60 / 100); ptr3[i] += (double)(ptr2[i] * 40 / 100);asptr3[i] = (ptr1[i] * 60 + ptr2[i] * 40) / 100.0;. I think that is way more readable.