gpt4 book ai didi

c - 在 C 中使用指针确定数据类型大小

转载 作者:行者123 更新时间:2023-11-30 18:27:56 25 4
gpt4 key购买 nike

#include <stdio.h>

int main()
{
int a, b, c, d;

char *p = (char *)0;
int *q = (int *)0;
float *r = (float *)0;
double *s = 0;

a = (int) (p+1);
b = (int) (q+1);
c = (int) (r+1);
d = (int) (s+1);

printf("%d %d %d %d", a, b, c, d);

return 0;
}

当我运行它时,它给出了输出

1 4 4 8

从输出中,我假设它给出了数据类型(char、int、float 和 double)的大小作为输出。但我不明白怎么办。有人可以解释一下这个程序吗? (char *)0 是什么意思? (int)(p+1) 有何作用?

提前致谢。

最佳答案

What does (char *)0 means?

它将 0 转换为指针。但这没有必要。你本来可以使用

    char *p = 0;

    char *p = NULL;

What does (int)(p+1) do?

p+1 计算结果为指针值。 (int) 部分将指针强制转换为 int。它适用于某些平台,因为 pp+1 之间的数值差为 sizeof(*p)

但是,请注意这是未定义的行为。不要在生产代码中使用它。使用标准支持的机制来获取类型的大小 - sizeof(type)

int a = sizeof(char);
int b = sizeof(int);
int c = sizeof(float);
int d = sizeof(double);

printf("%d %d %d %d", a, b, c, d);

您可以通过使用 size_t 作为变量来保留 sizeof 求值的类型。

size_t a = sizeof(char);
size_t b = sizeof(int);
size_t c = sizeof(float);
size_t d = sizeof(double);

printf("%zu %zu %zu %zu", a, b, c, d);

关于c - 在 C 中使用指针确定数据类型大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com