I'm going to take data structures course this year, so I decided to renew my knowledge about C by doing some simple tasks about pointers in C, and I have noticed one thing about passing pointers to functions, that I can't really understand.
Let's say we have a function:
void assignValueTen(int *var){
*var=10;
}
We can call this function from main like this:
int main( void ){
int x;
assignValueTen(&x);
printf("The value of x is %d.\n",x);
return 0;
}
The output of this would be:
The value of x is 10.
We can also call this function like this:
int main( void ){
int x, *y;
y=&x;
assignValueTen(y);
printf("The value of x is %d.\n",x);
return 0;
}
The output of this would also be:
The value of x is 10.
However, the statement below does not work as expected:
int main( void ){
int *x;
assignValueTen(x);
printf("The value of x is %d.\n",*x);
return 0;
}
Output of the code above is:
Process exited after 6.723 seconds with return value 3221225477
So, why does the code compile but not work as expected?
Is it because the pointer is not yet assigned to any address before in the last example?
Can somebody explain why this is happening in a little more detail?
Thanks a lot!