Why is the data type needed in pointer declarations?

前端 未结 8 657
萌比男神i
萌比男神i 2020-12-04 22:07

As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memo

8条回答
  •  情深已故
    2020-12-04 22:25

    Assume that this code compiles without error (as you would like):

    int a;
    int b = 42;
    void * d = &b;
    
    a = *d;
    

    What should be the value of a?

    Now with this one:

    int a;
    float b = 42.0;
    void * d = &b;
    
    a = *d;
    

    What do you expect in a?

    Actually the type specifies how should the pointed area be interpreted. You should specify int * in the first example and float * in the second one, instead of void *.

提交回复
热议问题