Declaring type of pointers?

前端 未结 10 2062
花落未央
花落未央 2020-12-01 05:20

I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:

int *point ;

As far as I know, pointers sto

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 05:44

    One reason is in pointer arithmetic. You cannot do p+1 unless you know the size of the element to which p points -- that is the size of the type to which p is a pointer. If you'd try p+1 on a void *p you're likely to get a bad answer (it is the same as if done on a char * but maybe you didn't want that; it is caught by -pedantic as a warning and by -pedantic-errors as an error).

    Another reason is type safety. If a function receives as argument an int * you cannot pass a pointer to char (a string) there. You'd get a warning (an error with -Werror / -pedantic-errors). Consider this (dummy) code:

    void test(int *x)
    {
    }
    
    int main()
    {
        char *x = "xyz";
        test(x);
        return 0;
    }
    

    Compiling (using gcc (GCC) 4.8.2 20131017 (Red Hat 4.8.2-1)) gives:

    1.c: In function ‘main’:
    1.c:8:2: warning: passing argument 1 of ‘test’ from incompatible pointer type [enabled by default]
      test(x);
      ^
    1.c:1:6: note: expected ‘int *’ but argument is of type ‘char *’
     void test(int *x)
          ^
    

提交回复
热议问题