C语言中的整数变量占用2字节还是4字节?它取决于哪些因素?

大多数教科书都说整型变量占用2个字节。 但是当我运行一个程序打印一个整数数组的连续地址时,它显示了4的差值。


当前回答

这个问题的答案取决于您使用的平台。 但无论平台如何,你都可以可靠地假设以下类型:

 [8-bit] signed char: -127 to 127
 [8-bit] unsigned char: 0 to 255
 [16-bit]signed short: -32767 to 32767
 [16-bit]unsigned short: 0 to 65535
 [32-bit]signed long: -2147483647 to 2147483647
 [32-bit]unsigned long: 0 to 4294967295
 [64-bit]signed long long: -9223372036854775807 to 9223372036854775807
 [64-bit]unsigned long long: 0 to 18446744073709551615

其他回答

#include <stdio.h>

int main(void) {
    printf("size of int: %d", (int)sizeof(int));
    return 0;
}

这个返回4,但它可能依赖于机器。

我知道它等于sizeof(int)int的大小实际上取决于编译器。在处理器是16位的时候,一个int是2字节。现在,在32位和64位系统上,它通常是4个字节。

不过,使用sizeof(int)是获得执行程序的特定系统的整数大小的最佳方法。

编辑:修正了在大多数64位系统上int为8字节的错误语句。例如,它在64位GCC上是4字节。

这是回答这个问题的一个很好的来源。

但这个问题是一种永远真实的回答:“是的。”两个。”

这取决于您的体系结构。如果您要在16位或更少的机器上工作,它不能是4字节(=32位)。如果您在32位或更好的机器上工作,则其长度为32位。

为了弄清楚,让你的程序准备输出一些可读的东西,并使用“sizeof”函数。返回您声明的数据类型的字节大小。但是要小心使用数组。

如果你声明int t[12];它将返回12*4字节。要得到这个数组的长度,只需使用sizeof(t)/sizeof(t[0])。 如果你要建立一个函数,它会计算发送数组的大小,记住If

typedef int array[12];
int function(array t){
    int size_of_t = sizeof(t)/sizeof(t[0]);
    return size_of_t;
}
void main(){
    array t = {1,1,1};  //remember: t= [1,1,1,0,...,0]
    int a = function(t);    //remember: sending t is just a pointer and equal to int* t
   print(a);   // output will be 1, since t will be interpreted as an int itselve. 
}

So this won't even return something different. If you define an array and try to get the length afterwards, use sizeof. If you send an array to a function, remember the send value is just a pointer on the first element. But in case one, you always knows, what size your array has. Case two can be figured out by defining two functions and miss some performance. Define function(array t) and define function2(array t, int size_of_t). Call "function(t)" measure the length by some copy-work and send the result to function2, where you can do whatever you want on variable array-sizes.

没有具体的答案。这取决于平台。它是由实现定义的。它可以是2 4或者别的什么。

int背后的思想是,它应该与给定平台上的自然“字”大小相匹配:16位平台上的16位,32位平台上的32位,64位平台上的64位,你明白了吧。然而,出于向后兼容性的考虑,一些编译器更倾向于在64位平台上使用32位整型。

2字节int的时代已经一去不复返了(16位平台?),除非你正在使用一些16位字长的嵌入式平台。你的课本可能很旧了。

这个问题的答案取决于您使用的平台。 但无论平台如何,你都可以可靠地假设以下类型:

 [8-bit] signed char: -127 to 127
 [8-bit] unsigned char: 0 to 255
 [16-bit]signed short: -32767 to 32767
 [16-bit]unsigned short: 0 to 65535
 [32-bit]signed long: -2147483647 to 2147483647
 [32-bit]unsigned long: 0 to 4294967295
 [64-bit]signed long long: -9223372036854775807 to 9223372036854775807
 [64-bit]unsigned long long: 0 to 18446744073709551615