0

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

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
DilDeath
  • 5
  • 3
  • 1
    @DilDeath, Try `void Func(int a[], int *b) { a[*b] = 1; *b += 5; }` and call it with `Func(a,&b);`. Is that change acceptable? – chux - Reinstate Monica Jun 14 '23 at 15:30
  • @chux-ReinstateMonica well it works but in my real program it does some anything except what i've expected to so i'll check on it thanks ! – DilDeath Jun 14 '23 at 15:35

2 Answers2

3
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 named b, but this copy is a pointer which may point to the b object in main. This allows us to modify the pointed-to object with *b += 5.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
1

For that you want to use a and b as a pointer, because a is an array and b you want to modify the value inside the function.

But you can't send directly b inside the function is why you to send as &b to give the address where the variable is stored in that way you don't copy the value of b but directly change it.

void foo(int *a, int *b) {
    a[*b] = 1;
    *b += 5;
}

int main(void) {
    int a[10] = {0};
    int b = 0;

    printf("b = [%i]\n", b);
    foo(a, &b);
    printf("a[0] = [%i]\n", a[b]);
    printf("b = [%i]\n", b);
}
Diamons
  • 76
  • 3