【发布时间】:2020-07-02 08:06:35
【问题描述】:
size_t size_int = sizeof(unsigned long int);
size_t size_ptr = sizeof(void*);
printf("sizeof(unsigned long int): %zu\n", size_int);
printf("sizeof(void*): %zu\n", size_ptr);
if(size_int == size_ptr) {
int a = 0;
void * ptr_a = &a;
// case 1
unsigned long int case_1 = *((unsigned long int*)&ptr_a);
printf("case 1: %lu\n", case_1);
// case 2
unsigned long int case_2 = (unsigned long int)ptr_a;
printf("case 2: %lu\n", case_2);
// case 3
unsigned long int case_3 = 0;
memcpy(&case_3, &ptr_a, sizeof(void*));
printf("case 3: %lu\n", case_3);
// case 4
void *ptr_b = NULL;
memcpy(&ptr_b, &case_3, sizeof(void*));
int *ptr_c = (int*)ptr_b;
*ptr_c = 5;
printf("case 5: %i\n", a);
}
事实上,我知道 C99 中有 uintptr_t 和 intptr_t。但是,出于教育目的,我想问一些问题。在开始之前,我知道这是一种不好的做法,绝不应该以这种方式进行。
第一季度。案例 1 会导致未定义的行为吗?安全吗?如果不是,为什么?如果它是安全的,是否可以保证“case_1”变量与 unsigned long int 具有完全相同的地址?
Q2。案例 2 同上。
Q3。案例 3 同上。
Q4。案例 4 同上。
【问题讨论】:
标签: c type-conversion pointer-conversion