Answers/Solutions to Exercises in Chapter 4, Exercise 3

E3: Consider a simple program:
    #include <stdio.h>
    #include <string.h>

    int main()
    {   
        char* p;

        p = malloc(20);
        strcpy(p,"hello");

        printf("%s\b",p);
        return 0;
    }

The C compiler gives a strange warning message:
line 8: warning: assignment makes pointer from integer without a cast

yet it works correctly when executed. What is your explanation, considering that C compilers should allow void* stored in char* without complaining?

A3: Since we did not include <stdlib.h>, the compiler actually dos not "know" the signature of malloc(), hence it assumes by default, that it returns int. Thus, it interprets p = malloc(20); as an attempt to store an integer in a pointer and warns us about it. However, the address returned by malloc() is correct no matter how interpreted, so it works fine.

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