sách gpt4 ăn đã đi

c - void 指针 = int 指针 = float 指针

In lại 作者:太空狗 更新时间:2023-10-29 14:50:15 29 4
mua khóa gpt4 giày nike

我有一个指向内存地址的vô hiệu 指针。然后,我做

  • số nguyên 指针 = vô hiệu con trỏ

  • trôi nổi 指针 = vô hiệu con trỏ

然后,取消引用它们以获取值。

{
int x = 25;

void *p = &x;
int *pi = p;
float *pf = p;
double *pd = p;

printf("x: n%d\n", x);
printf("*p: %d\n", *(int *)p);
printf("*pi: %d\n", *pi);
printf("*pf: %f\n", *pf);
printf("*pd: %f\n", *pd);

trả về 0;
}

取消引用 số pi(số nguyên 指针)的输出是 25。但是,取消引用 pf(trôi nổi 指针)的输出是 0.000。还 dereferncing pd(gấp đôi pointer) 输出一个负分数,保持改变?

为什么会这样,是否与字节顺序有关(我的 CPU 是小字节序)?

câu trả lời hay nhất

theo C 标准,您可以将任何指针转换为 void * 并将其转换回来,效果相同。

引用 C11,章节 §6.3.2.3

[...] A pointer to any object type may be converted to a pointer to vô hiệu and back again; the result shall compare equal to the original pointer.

这就是为什么当您将 void 指针转换为 int *、取消引用并打印结果时,它会正确打印。

但是,标准不保证您可以取消对该指针的引用,使其成为不同的数据类型。它本质上是在调用未定义的行为。

因此,取消引用 pf hoặc pd 以获得 trôi nổi hoặc gấp đôi Đúng undefined behavior ,因为您正在尝试读取分配给 số nguyên 作为 trôi nổi hoặc gấp đôi 的内存。有一个明显的错误案例导致了 UB。

要详细说明,số nguyêntrôi nổi(和 gấp đôi)具有不同的内部表示,因此尝试将指针转换为另一种类型,然后尝试取消引用以获取其他类型的值 是行不通的。

相关,C11,章节 §6.5.3.3

[...] If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

Giá trị không hợp lệ部分,(强调我的)

Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.

关于c - void 指针 = int 指针 = float 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34399869/

29 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress