Does pointer arithmetic have uses outside of arrays?

后端 未结 7 2016
青春惊慌失措
青春惊慌失措 2020-12-17 15:00

I think I understand the semantics of pointer arithmetic fairly well, but I only ever see examples when dealing with arrays. Does it have any other uses that can\'t be achie

7条回答
  •  不思量自难忘°
    2020-12-17 15:35

    Here's a case for pointer arithmetic outside of (strictly defined) arrays:

    double d = 0.5;
    unsigned char *bytes = (void *)&d;
    for(size_t i = 0; i < sizeof d; i++)
        printf("Byte %zu of d is %hhu\n", i, bytes[i]);
    

    Why would you do this? I don't know. But if you want to look at the bitwise representation of an object (useful for things like memcpy and memcmp), you'll need to cast their addresses to unsigned char *s (or signed char *s if you like) and work with them byte-by-byte. (If your task isn't too difficult you can even write the code to work word-by-word, which most memcpy implementations will do. It's the same principle, though, just replace char with int32_t.)

    Note that, in the standard, the exact values (or the number of values) that are printed are implementation-defined, but that this will always work as a way to access an object's internal bytewise representation. (It is not required to work for larger integer types, but almost always will - no processor I know of has had trap representations for integers in quite some time).

提交回复
热议问题