int f(int *x)
{
*x = 5;
return *x;
}
int main()
{
int * y = 0;
int z = f(y);
}
Why does this code give me a run time error?
Why does this code give me a run time error?
Because y is a NULL pointer, which is dereferenced in f(). Note, it is undefined behaviour to dereference a NULL pointer.
Can you return an integer by dereferencing a pointer?
Yes, assuming the pointer is pointing to a valid int. For example:
int main()
{
int y = 0;
int z = f(&y);
}
You can, if a pointer points to some valid memory. In your case, you are dereferencing a NULL (0x00) pointer, which is undefined behavior (aka UB). This, for example, works fine:
int f(int *x)
{
*x = 5;
return *x;
}
int main()
{
int value = 1986;
int *y = &value; // Point to something valid.
int z = f(y);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With