Questions and Answers
Q: One of the difficulties with pointers is that often when we misuse them, our errors are not caught by the compiler at compile time; they occur at runtime. Which of the following result in compile-time errors? Which of the following result in runtime errors? Why?
a) char *sptr = "abc",*tptr; *tptr = sptr; | b) char *sptr = "abc",*tptr; tptr = sptr; |
c) char *sptr = "abc",*tptr; *tptr = *sptr; | d) int *iptr = (int *)10; *iptr = 11; |
e) int *iptr = 10; *iptr = 11; | f ) int *iptr = (int *)10; iptr = NULL; |
A: a) A compile-time error occurs because when we
dereference tptr, we get a character,
whereas sptr is a pointer to a character.
Thus, the code is trying to assign a character pointer to a character,
which is a type conflict. b) No error occurs because both
tptr and sptr
are character pointers. c) A runtime error is likely to occur because
no storage has been allocated for tptr.
When we dereference tptr, we cannot be sure
where it points. d) A runtime error is likely to occur because
assigning an integer pointer a fixed address is dangerous. When
dereferencing iptr, we try to write 11 at
address 10, which is probably invalid. e) A compile-time error or
warning occurs because the code is trying to initialize an integer
pointer to an integer, which is a type conflict. f ) No error occurs
because although the code first performs the dangerous step of
initializing iptr to a fixed address, it is
then immediately reset to NULL, which is valid.
Q: Recall that calculations with ...