Reputation: 498
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);
}
Upvotes: 0
Views: 257
Reputation: 174
You need to use %f
or %lf
to print a double
value. Printing by using %d
will print an integer value where your array ptr3
is of type double
.
void printResult(double* ptr3) {
for (int i = 0; i < 10; i++) {
printf("%f ", *(ptr3 + i));
}
}
Upvotes: 0
Reputation: 5872
As pointed out by people in comments there are some problems in your code:
ptr3[i]
, since all variables in calculation expression are integer, you're getting integer as result being assigned to a double variable. You need to use a floating point number so that you get precise results:ptr3[i] = (double)(*(ptr1 + i) * 60.0 / 100);
printResult()
. You are printing a double value, you should use %f
or %lf
instead:printf("%lf ", *(ptr3 + i));
When I apply these changes, I'm able to see ptr3
array printed properly:
c-posts : $ gcc sum2arrays.c
c-posts : $ ./a.out
84.599998 52.200001 69.799999 89.200001 37.400000 47.200001 77.000000 47.799999 34.000000 57.200001
Upvotes: 1