To prevent the dreaded core dump (or at least some of them) we need to give our pointers useful values.
&
) operator does.
We've seen it in doing calls to scanf()
, but we've never really
studied it.
An expression such as &x
is evaluated to be the address
of the variable x
and the expression has type "pointer to
foo
" where x
is of type foo
.
Take for example the following code fragment:
int x, *x_ptr ; x_ptr = &x ; x = 5 ; printf( "%d\n", *x_ptr ) ;
p
points to some object and
that q
is a pointer of the same type as p
.
The statement:
q = p ;
p
and q
point to the same thing.
This is clear when we remember that the value of a pointer is the
address of the thing to which it points.
Assigning one variable to another copies the value of the variable on
the right to the one on the left.
After such an assignment, the pointer on the left now has the same
value as the one on the right which means that it points to the same
object.
malloc()
.
malloc()
takes as an argument the number of bytes which
we want to allocate and it returns a pointer to the new object.
The usual way we use malloc()
is:
p = (foo *)malloc( sizeof( foo )) ;
p
is a pointer to a foo
.
The (foo *)
preceding the
malloc()
tells the compiler to
convert the pointer malloc()
returns to a pointer to a
foo
.
malloc()
has no way of knowing what type of object you want to
point to, only how big it is.
The sizeof( foo )
evaluates to the number of bytes in a
foo
.
This is a portable way of determining the size of an object.
p
is a pointer to a character,
c
is a character,
q
is a pointer
to an integer and x
is an integer.