c - int *p 应该改为 long int *p 吗?

标签 c

我正在通过阅读 K&R 和做练习来学习 c。我现在在讨论指针的第 5 章。我不明白为什么声明:

int *p;

不是:

long int *p;

因为 *p 包含地址并且不能保证 int 类型的变量足够大以容纳大地址。或者有吗?

最佳答案

int 是指针指向的对象的类型,而不是指针本身的大小。指针的大小与其指向的对象无关

例如:

int *p;

double *d;

指针 p 和 d “通常”具有相同的大小,但它们指向的数据不具有相同的大小。

编辑:正如评论中指出的那样,指针实际上并不“需要”具有相同的大小。

正如约翰所解释的:

For instance, a char * on a word-addressed system may actually be larger than an int *, since it needs to specify an offset into the word. The only guarantees are that void * and char * have the same alignment and representation, that pointers to compatible types have the same alignment and representation, that pointers to struct types have the same alignment and representation, and pointers to union types all have the same alignment and representation

关于c - int *p 应该改为 long int *p 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6051408/

相关文章:

c - 重新分配后如何将新内存清零

C:通过堆栈/寄存器问题返回值

c - 米斯拉 11.3 : cast from int to pointer

c - 16 KB 由 OS X 上的 getc 和 fprintf 分配

c - 了解管道、fork 和 exec - C 编程

c++ - 你能解释一下下面的 C/C++ 语句吗?

C 字符串函数

c - 如何在编码和解码时正确处理文件?

使用 char 和 int 变量在 c 中创建数值表达式

c - 从链表末端删除节点