#include <stdio.h>
void readMatrix(int*a,int*b){
int r,c;
scanf("%d%d",&r,&c);
a = &r;
b = &c;
}
main(){
int a,b;
readMatrix(&a,&b);
printf("%d\n%d",a,b);
}
When i run it and insert values 1 and 2 and print the a,b variables in main 1697527160 and 1700556911. I know that i could simply scan the a,b values in main but what's the fault in my code?
You are taking the address of two local variables r
and c
, to modify local variables a
and b
. These only exist in the scope of the function. The caller sees no effect from this. Even if you managed to get a
and/or b
out of the function, they would be dangling pointers, since the objects they point to do not exist outside of the function.
You can fix these problems by using the pointers passed to the function directly. This lets the scanf
function write to the location pointed ay by those pointers:
void readMatrix(int*a, int*b) {
scanf("%d%d", a, b);
}