Not casting pointers in C can cause problems?

前端 未结 6 1702
梦谈多话
梦谈多话 2021-02-07 15:21

Yesterday I was in class, and at some point the instructor was talking about C code. He said:

What is the purpose of making a pointer cast in C? The only

6条回答
  •  再見小時候
    2021-02-07 15:41

    Casting from void* to a type i need in my program (e.g. int*, char*, struct x*) makes sense to me. But casting across other types i.e. int* to char* etc. can become problematic (due to the offsets being different for ints, chars etc). So be careful if doing so.

    But ... to specifically answer your question, consider the following:

    int_pointer = malloc(2 * sizeof(int)); // 2 * 4 bytes on my system.
    *int_pointer = 44;
    *(int_pointer + 1 )= 55;
    
    printf("Value at int_pointer = %d\n", *int_pointer); // 44
    printf("Value at int_pointer + 1 = %d\n", *(int_pointer + 1)); // 55
    

    (The offsets above will be in 4 byte increments.)

    //char_pointer = int_pointer; // Gives a warning ...
    char_pointer = (char*)int_pointer; // No warning.
    printf("Value at char_pointer = %d\n", *char_pointer); // 0
    printf("Value at char_pointer = %d\n", *(char_pointer+1)); // 0
    printf("Value at char_pointer = %d\n", *(char_pointer+2)); // 0
    printf("Value at char_pointer = %d\n", *(char_pointer+3)); // 44 <==
    

    Four bytes were allocated to the int value of 44. Binary representation of 44 is 00101100 ... the remaining 3 bytes are all 0s. So when accessing using char* pointer, we increment 1 byte at a time and get the above values.

提交回复
热议问题