#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
void test (int a,int *b, int result[], int serie[]);
int main()
{
int *serie = malloc(sizeof(int));
int result[20], a,b, i;
a=0;
b=0;
for (i = 0; i < 20; i++) {
result[i]=i+10;
serie[i]=rand();
printf("result is %d \n",result[i]);
}
test(a,&b,result,serie);
printf("value of a inside main %d \n",a);
printf("value of b inside main %d \n",b);
for (i = 0; i < 20; i++) {
printf("value of result inside main is %d and of serie is %d \n",result[i],serie[i]);
}
getchar();
return 0;
}
void test(int a, int *b, int result[], int serie[]) {
int i;
a=13;
*b=14;
printf("value of a inside the function %d \n",a);
printf("value of b inside the function %d \n",*b);
for (i = 0; i < 20; i++) {
result[i]=result[i]*2;
serie[i]=7;
printf("value of result inside the function is %d and of serie is %d\n",result[i],serie[i]);
}
}
Basically, all this code does is seeing the scope of the variables, I wrote it to help myself I thought as to change the value of the integer inside main with a function (see int b) You have to call it with &b (test(a,&b,result,serie);) and then inside the function *b. So I was trying those kind of operations &* with the arrays but They did not work.
It seems all you have to do It is write the array void test(... int result[],int serie[]) and to call the function just put the name with no brackets at all: test(...,result,serie); am I right?
What if I only want to change the arrays inside the function like with variable a?
Yes, that is correct. In order to modify arrays, all you need to do is declare it like:
or this:
Both the above are equivalent.
Why this is true is that you’re passing in a pointer, which gets passed by value. This is distinct from the array itself, which is passed by reference (via the pointer). So the pointer is copied, and if you tried to actually change the value of result without using
*, it wouldn’t last outside the function. If you want to modify the arrays inside the function without modifying the originals, you have to copy them, either before you pass it in or after.