C结构有任何尺寸限制吗?

时间:2011-10-11 10:46:36

标签: c structure

C结构有任何尺寸限制吗?

3 个答案:

答案 0 :(得分:12)

来自C标准:

  

5.2.4.1翻译限制

     

1实施应至少能够翻译和执行   一个程序,其中至少包含一个实例   以下限制:

     

...    - 对象中的65535个字节(仅限托管环境中)
  ...    - 单一结构或工会中的1023名成员
  ...    - 单个中63个级别的嵌套结构或联合定义   结构声明列表   ...   13)实施应避免强加固定的翻译限制   只要有可能。

除此之外,上限为SIZE_MAXsize_t的最大值)。

答案 1 :(得分:6)

由于sizeof运算符会产生size_t类型的结果,因此限制应为SIZE_MAX

您可以像这样确定SIZE_MAX的值:

#include <stdint.h>
#include <stdio.h>

int main (void) {
  printf("%zu", SIZE_MAX);
  return 0;
}

这是编译器应该允许的内容。运行时环境允许的是另一个故事。

实际上在堆栈(本地)上声明一个类似大小的对象将无法工作,因为堆栈可能比SIZE_MAX小得多。

全局拥有这样的对象可能会使程序启动时抱怨可执行加载程序。

答案 2 :(得分:2)

实证分析

在实践中,像GCC这样的实现似乎只允许小于size_t的结构,可能受PTRDIFF_MAX的约束。另见:What is the maximum size of an array in C?

使用:

 for i in `seq 32`; do printf "typedef struct { S$i x; S$i y; } S$(($i+1));\n"; done

我们制作节目:

#include <stdint.h>
#include <stdio.h>

typedef struct { uint8_t i; } S0;
typedef struct { S0 x; S0 y; } S1;
typedef struct { S1 x; S1 y; } S2;
typedef struct { S2 x; S2 y; } S3;
typedef struct { S3 x; S3 y; } S4;
typedef struct { S4 x; S4 y; } S5;
typedef struct { S5 x; S5 y; } S6;
typedef struct { S6 x; S6 y; } S7;
typedef struct { S7 x; S7 y; } S8;
typedef struct { S8 x; S8 y; } S9;
typedef struct { S9 x; S9 y; } S10;
typedef struct { S10 x; S10 y; } S11;
typedef struct { S11 x; S11 y; } S12;
typedef struct { S12 x; S12 y; } S13;
typedef struct { S13 x; S13 y; } S14;
typedef struct { S14 x; S14 y; } S15;
typedef struct { S15 x; S15 y; } S16;
typedef struct { S16 x; S16 y; } S17;
typedef struct { S17 x; S17 y; } S18;
typedef struct { S18 x; S18 y; } S19;
typedef struct { S19 x; S19 y; } S20;
typedef struct { S20 x; S20 y; } S21;
typedef struct { S21 x; S21 y; } S22;
typedef struct { S22 x; S22 y; } S23;
typedef struct { S23 x; S23 y; } S24;
typedef struct { S24 x; S24 y; } S25;
typedef struct { S25 x; S25 y; } S26;
typedef struct { S26 x; S26 y; } S27;
typedef struct { S27 x; S27 y; } S28;
typedef struct { S28 x; S28 y; } S29;
typedef struct { S29 x; S29 y; } S30;
/*typedef struct { S30 x; S30 y; } S31;*/
S30 s;

int main(void) {
    printf("%jx\n", (uintmax_t)sizeof(s));
    return 0;
}

然后在Ubunbu 17.10:

$ arm-linux-gnueabi-gcc --version
arm-linux-gnueabi-gcc (Ubuntu/Linaro 7.2.0-6ubuntu1) 7.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ arm-linux-gnueabi-gcc -std=c99 main.c

的工作原理。但是如果我们取消注释S31,它就会失败:

main.c:35:16: error: type ‘struct <anonymous>’ is too large
typedef struct { S30 x; S30 y; } S31;

因此最大尺寸介于2 ^ 30和(2 ^ 31 - 1)之间。

然后我们可以将S30转换为:

typedef struct { S29 x; S29 y; uint8_t a[(2lu << 29) - 1]; } S30;

并且我们确定此实现的最大大小为2^31 - 1 == PTRDIFF_MAX

相关问题