This is my example code:
#include <stdio.h>
void Func(int a[], int b) {
a[b] = 1;
b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b);
Func(a, b);
printf("%d\n", a[0]);
printf("%d\n", b);
}
And I want the program to print:
0
1
5
I’ve tried changing the function by making b a pointer:
void Func(int a[], int *b)
… and by writing *b += 5. Also, I’ve changed the call of the function to:
int a[10];
int *b = 0;
// ...
Func(a, &b);
Is it possible to manipulate b and to use it?
Note: I’ve tried following this post
>Solution :
void Func(int a[], int b){ a[b] = 1; // OK b += 5; // useless }
The problem with this code is that Func is assigning a local copy of b, and this has no effect outside of the function.
To get the expected output:
#include <stdio.h>
void Func(int a[], int *b) {
a[*b] = 1;
*b += 5;
}
int main(void) {
int a[10];
int b = 0;
printf("%d\n", b); // print value of b
Func(a, &b); // pass address of b to Func
printf("%d\n", a[0]);
printf("%d\n", b); // print value of b again
}
Func still has a local copy of b, but this copy is a pointer. This allows us to modify the pointed-to object with *b += 5.