Answers/Solutions to Exercises in Chapter 3, Exercise 8

E8: In our C program we have
    char* p;
    ...
    p = "ab";

and the compiler does not complain and the program works fine. If we change it to
    int* p;
    ...
    *p = 23;
will everything work fine as well?

A8: No, the second program will compile with a warning (if the compiler is any good) that the local variable p has not been initialized. When running the program, it will most likely crash. The explanation is simple.
In the former case, the compiler stores somewhere in memory the string "ab" and the statement will just make p point to that location. So everything is fine (as long as you later on do not try to deallocate p !!).
In the latter case, p is not initialized, so it points to an arbitrary location, and that is where the program is trying to store the value 23. (In most compiler p will in fact point to 0, a forbidden location.) Most likely, the program will be terminated for memory access violation.

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 3 Index