Why does this function incorrectly multiply the values in the array by the given number?
I am trying to write a function in C that takes a pointer to an array and returns that pointer with all the values multiplied by multiple. I have:
int* returnNpledArray(int *a, int n){
int i = 0;
for(i = 0; i < SIZE; i++){
*a++ *= n;
}
return a;
}
but when I call it, what I do is basically like this:
int sample2[] = {-10,-8,-6,-4,-2,0,2,4,6,8};
returnNpledArray(sample2, 3);
int d = 0;
for (d = 0; d < SIZE; d++){
printf("%d\n", *sample2);
}
the whole array prints as soon as the first value in it, multiplied by n. I thought that since in the function I say * a ++ * = n; that I am both dereferencing the value at that location in AND, incrementing the pointer. How can I get this to work?
source to share
If you only want to iterate with pointers, you can use the following:
int *current = sample;
int *end = sample + SIZE;
for ( ; current < end; current ++) {
printf("%d\n", *current);
}
Note that we are advancing the pointer current
here to point to the next one int
; Also, it end
is a pointer that only points to the last element in the array sample
.
source to share
As mentioned above, you just print the first value
#include<iostream>
using namespace std;
#define SIZE 10
int* returnNpledArray(int *a, int n){
int i = 0;
for(i = 0; i < SIZE; i++){
*a++ *= n;
}
return a;
}
int main()
{
int sample2[] = {-10,-8,-6,-4,-2,0,2,4,6,8};
returnNpledArray(sample2, 3);
int d = 0;
for (d = 0; d < SIZE; d++){
printf("%d\n", sample2[d]);
}
}
Output
-30
-24
-18
-12
-6
0
6
12
18
24
Program ended with exit code: 0
source to share
The typical way to write code would be a[i] *= n;
. You also neglected to point out where it is SIZE
defined, which could be a bug.
Be that as it may, the increment has to happen, return the pre-incremented value, play out, read, modify, write. The multiplication code should work.
Ultimately, it really is your fault printing function. It is not a repetition of an array. Tryprintf("%d\n", sample2[d]);
source to share
Why are you making it difficult when multiplying? I think you can do it like this.
int* returnNpledArray(int *a, int n){
int i = 0;
for(i = 0; i < SIZE; i++){
a[i] = a[i]*n;
}
return a;
}
Here is the main function
int sample2[] = {-10,-8,-6,-4,-2,0,2,4,6,8};
returnNpledArray(sample2, 3);
int d = 0;
for (d = 0; d < SIZE; d++){
printf("%d\n", sample2[d]);
}
I am assuming SIZE is the size of the array.
source to share