0

在下面的代码片段中,指针地址和值被引用为 type size_t。然而,正如标题所说,最后的减法对我来说没有意义。它的作用就像是减去乘以 8 的数字,而不是int array.

#include <stdio.h>
#include <stdint.h>

int main()
{
    int i[6] = {2, 0, 1, 0, 20, 24};

    void *ptr = &i[2];

    printf("%zu\n", ((size_t*)ptr));
    printf("%zu\n", *((size_t*)ptr));
    printf("%zu\n", ((size_t*)ptr) - *((size_t*)ptr));
}
4

2 回答 2

3

First thing to note is that you're accessing a signed integer variable through a pointer to an unsigned integer variable. Also note that sizeof(size_t) may not necessarily equal sizeof(int)!

The line:

printf("%zu\n", ((size_t*)ptr) - *((size_t*)ptr));

Effectively Does AddressOf(i[2]) - i[2], which is AddressOf(i[2]) - 1.

In C pointer arithmetic the address is decremented not by 1, but by 1 * sizeof(data type), which is whatever sizeof(size_t) is on your machine. If you're on a 64-bit machine this could be 8 bytes. This the address you get will be -8 and not, as I think you're expecting, -1...

EDIT: The %z could probably be %p for pointer addresses. The casts to size_t * are not needed and could be dangerous as discussed above...

于 2013-09-23T16:18:57.557 回答
0

您正在i[2] == 1size_t指针中减去,因此实际差异为sizeof(size_t) == 8.

于 2013-09-23T16:21:01.907 回答