[英]C Constant structures containing arrays of different lengths on the stack
我有兴趣在C中创建一个结构(在其他POD类型中)包含一个数组,然后在堆栈上创建它的全局实例。 数组长度在编译时是已知的,但对于每个结构实例将是不同的。 struct的每个实例中的值都不会改变,因此应该设置为const。
目前我有以下代码:
#ifdef __cplusplus
extern "C" {
#endif
#include "stdio.h"
typedef struct A
{
int x;
int y;
int* z;
} A_t;
const A_t test[2] = { {1,1, (int[3]){1,1,1} },
{2,2, (int[5]){2,2,2,2,2} }
};
int main( void )
{
printf( "test[0]: %d %d (%d, %d, %d)\n",
test[0].x,
test[0].y,
test[0].z[0],
test[0].z[1],
test[0].z[2] );
printf( "test[1]: %d %d (%d, %d, %d, %d, %d)\n",
test[1].x,
test[1].y,
test[1].z[0],
test[1].z[1],
test[1].z[2],
test[1].z[3],
test[1].z[4] );
printf( "\n\n" );
return;
}
#ifdef __cplusplus
}
#endif
这将是一个嵌入式系统,其中堆非常有限,所以我想避免malloc,除非我绝对必须。 如果可能的话,我也想坚持使用C89,因为VS2008不支持C99(我认为)。
这在GCC(通过MinGW 4.8.1)中工作正常,但在Visual Studio 2008中无法编译。有没有人有任何关于如何让它在两个编译器上工作的建议?
作为参考,这是来自VS2008的错误消息:
c:\\ temp \\ test_variable_length_arrays \\ bob.c(15):错误C2059:语法错误:'{'
c:\\ temp \\ test_variable_length_arrays \\ bob.c(15):错误C2059:语法错误:'}'
c:\\ temp \\ test_variable_length_arrays \\ bob.c(17):错误C2059:语法错误:'}
提前感谢所有评论。
您可以全局分配内部结构,然后在运行时分配到结构中,例如
int x[] = {1,1,1};
int y[] = {3,3,3,3,3};
int main()
{
A_t str = {2, 2, y};
}
我相信一些编译器也会让你将str
的定义移动到全局范围,使其完全静态。
Visual Studio令人窒息:
const A_t test[2] = { {1,1, (int[3]){1,1,1} },
{2,2, (int[5]){2,2,2,2,2} }
具体来说, 复合文字 (int[3]){1,1,1}
和(int[5]){2,2,2,2,2}
; 复合文字是用C99引入的,不会被Visual Studio等C89编译器识别。
这是否必须由Visual Studio编译? 您可以使用MinGW(Windows原生GNU编译器)或使用cygwin下的gcc构建它吗? 如果没有,slugonamission的解决方案可能会成为阻力最小的路径。
请参阅有关(int[3]){1,2,3}
语法的注释。 但是不能保证那些阵列会在内存中存在(它们是临时的)。 您可以将它们定义为全局变量,并设置指向它们的指针:
static int az1[] = {1, 2, 3};
static int az2[] = {1, 2, 3, 4, 5};
const A_t test[2] = { {1,1, az1 },
{2,2, az2 }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.