Why do we have pointers other than void

前端 未结 10 973
攒了一身酷
攒了一身酷 2020-12-30 22:54

I know that we have different pointers like int, float, and char. A void pointer is the only pointer which can hold all o

10条回答
  •  天命终不由人
    2020-12-30 23:06

    When you iterate through the memory block pointed to by a pointer, it's necessary to know the size of the data type the memory contains. Say you have two pointers, a charcharptr and an intintptr, both pointing at memory at byte X. charptr+1 will point to the byte X+1, while intptr+1 will point to byte X+4.

    A quick and dirty piece of badly written code to illustrate that:

    #include 
    
    int main()
    {
        char * cptr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        short * sptr = (short*)cptr;
        int * iptr = (int*)cptr;
        long long * lptr = (long long*)cptr;
    
        printf ("CHAR: %d, +1: %d\n",cptr,cptr+1);
        printf ("SHORT: %d, +1: %d\n",sptr,sptr+1);
        printf ("INT: %d, +1: %d\n",iptr,iptr+1);
        printf ("LONG LONG: %d, +1: %d\n",lptr,lptr+1);
    }
    

    This should:

    • generate warnings about casting pointers of different sizes (type safety),
    • output identical numbers in the first column (all pointers point to the same address in memory), but different numbers in the 2nd column (which is base address + size of the pointer's type: 1, 2, 4 and 8 bytes).

提交回复
热议问题