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
&xis evaluated to be the address of the variable
xand the expression has type "pointer to
xis of type
Take for example the following code fragment:
int x, *x_ptr ; x_ptr = &x ; x = 5 ; printf( "%d\n", *x_ptr ) ;
which prints out 5.
ppoints to some object and that
qis a pointer of the same type as
p. The statement:
q = p ;
will make both
qpoint 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()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
p = (foo *)malloc( sizeof( foo )) ;
pis a pointer to a
(foo *)preceding the
malloc()tells the compiler to convert the pointer
malloc()returns to a pointer to a
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.
Which of these are valid assignment to pointers? Assume that
pis a pointer to a character,
cis a character,
qis a pointer to an integer and
xis an integer.