Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the value of a variable passed as an argument and also use the value for an array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading