Even after years of C, pointers still confuse me.
Are these two the same:
int *num;
someFunc(num)
and
int num;
someFunc(&num);
Declaring a variable with *
makes it a pointer, &
turns a variable (momentarily) into a pointer?
Even after years of C, pointers still confuse me.
Are these two the same:
int *num;
someFunc(num)
and
int num;
someFunc(&num);
Declaring a variable with *
makes it a pointer, &
turns a variable (momentarily) into a pointer?
No they are not the same. In the first case you have a pointer which is pointing to some random memory location (as you have not initialized it). In the second case, the pointer obtained in someFunc
will be pointing to a valid location (the address of variable num
).
They are the same in terms of the function call. However
The difference is....
int num
is an actual integer, which you take the address of. Which can then be placed into a pointer
int *num
is a pointer to an int, however, with your code as is, it does not point to an actual int that can hold a value.
so only the second example is working code.
first one would be working if...
int x;
int *num = &x;
someFunc(num)
someFunc would look like
void someFunc(int *blah)
{
}
so basically int* num = &x
is whats going on when you do the function call someFunc(&num)
ie, its effectively just doing int* blah = &num
The second passes the address of the integer num
, a perfectly reasonable thing to do. The first passes whatever happens to be stored in the pointer num
. That should be the address of an int
, but in your example num
is uninitialized and the address probably points to garbage (at best).
&
doesn't "turn a variable into a pointer", its an operator that returns the address of the variable. Which is, by definition, a pointer. Hence, no difference, the function someFunc
receives a pointer value either way (in the first case it receives a copy the value of the pointer variable, in the second case it receives a copy of the return value of the operator &
).
In the first case, you're declaring num
to be a pointer to an integer. In the second case num
is an integer.
To the someFunc
function, in both cases the argument passed is a pointer to integer. So, to print the value you'll need to dereference printf("%d\n", *num)
.
In both cases the value would be some garbage since you haven't initialized.
Hope that helps.
Update On FreeBSD I got segmentation fault with the first one since the pointer which is not initialized may have pointed to somewhere that it is not supposed to.