C编译器中的变量大小是否依赖?

Is Variable size in C compiler dependent?

考虑以下代码:

void print(int arr[])
{
  int n = sizeof(arr)/sizeof(arr[0]);
  printf("\nSize is  %d",n);
}

int main()
{
    int arr[]={1,2,3,4,5,6};
    print(arr);
    return 0;
}

反之,我们以前研究过,当一个数组作为参数传递时,它只传递数组的基地址(对于隐式指针变量和整数,它是4个字节变量两者 )。

变量大小是否依赖于编译器,或者我在这里遗漏了什么?请指正

arr[]作为函数参数,是一个指针。 sizeof(arr)/sizeof(arr[0]); 是 pointer/size 或 int 的大小。不涉及阵列。

Is Variable size in C compiler dependent?

是的,int 可以是 32 位、16 位等1(必须至少为 16)

对象指针可以是 16 位、32 位、64 位等1(必须至少为 16)

指针通常比 int 更宽,但也可能相同或(很少)更小。该比率可以是 2/1 或 1/1 或其他。


1 其他大小也是可能的并且已被采用,例如 36 位 int 或 48 位对象指针。这是 C 能够采用几乎所有曾经制造的处理器并且可能适用于所有新处理器的能力。灵活性是以 可移植 代码必须考虑这些变化为代价的。

Are the variable sizes compiler dependent ? 是的,这取决于编译器,但这并不意味着体系结构的观点无关紧要。它还取决于架构是否是 16/32/64 位系统,例如,在 16-bit 机器中,sizeof (int)2 字节,在 32-bit 机器中是 [=16] =]字节。

它被认为 int 是处理器的本机大小,即寄存器的大小。

这里的函数参数 arr[] 是指针而不是数组。

所以如果系统是 32 位系统那么

sizeof(arr)/sizeof(arr[0]);

将导致 14/4 = 1

我发现@Eric 关于编译器和架构在定义变量大小方面的作用的评论非常真实且有趣。

The sizes of types are ultimately determined by the C implementation (notably the compiler), not the architecture or the operating system. While C implementations are usually heavily influenced by the architecture, computers are effectively Universal Turing Machines, so that any desired choices for sizes can be implemented. C implementations sometimes choose sizes based on considerations of what source code is to be supported rather than what is most efficient for the architecture. They may even support a choice of sizes via command-line switches.

是的,类型的大小取决于实现。特别是,指向 int 的指针的大小和 int 的大小取决于 C 实现(主要是编译器),并且可能彼此不同。

题中“数组的基地址(隐式指针变量和整型变量均为4字节)”中的断言一般为假.在某些 C 实现中为真,但在其他实现中为假。

void print(int arr[]) 声明的函数内的代码 sizeof(arr)/sizeof(arr[0]) 打印指向 int 的指针的大小除以 int.[=16= 的大小]

虽然 C 实现在很大程度上受其目标体系结构和操作系统的影响,但它们可能会出于执行速度以外的原因选择其类型的大小,例如支持较小内存使用的目标、支持不支持的代码编写为完全可移植到任何类型大小,或支持更轻松地使用大整数。