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

My program returns 4 instead of expected value 40

#include <stdio.h>
    
int value(int *a);
    
int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

int value(int *a){
    int c = (*a)*10;
    return c;
}

In this code, I transfer the address in function but it does not change, Why?

>Solution :

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

You have 2 ways of having a function change data outside it, you can pass a variable by reference and update it or you can return a value and use that. You are mixing half of each method (I reordered the code to make my commentary clearer)

  #include <stdio.h>
    
    int value(int *a);
    

// here you are passing by reference, good
int value(int *a){
    int c = (*a)*10; // but you dont change a
    return c;  // instead you return a new value
}

 int main(){
        int num = 4;
        value(&num); // but here you ignore the new value. 
        printf("value of number is = %d", num);
        return 0;
    }

to make reference way work you need

#include <stdio.h>
    
void value(int *a);
    
int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

void value(int *a){
    *a = (*a)*10; // chnage the value that a points at
    // no need to retunr anything
}

or to make the return way work

#include <stdio.h>
    // no need to pass by reference
int value(int a);
    
int main(){
    int num = 4;
    num = value(num); // use value return by function
    printf("value of number is = %d", num);
    return 0;
}

int value(int a){
    int c = a * 10;
    return c;
}
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