静态数组定义为未指定大小,空括号? [英] static arrays defined with unspecified size, empty brackets?
问题描述
对于下面的C ++代码片段:
For the C++ code fragment below:
class Foo {
int a[]; // no error
};
int a[]; // error: storage size of 'a' isn't known
void bar() {
int a[]; // error: storage size of 'a' isn't known
}
为什么isn是成员变量也会导致错误?这个成员变量的含义是什么?
why isn't the member variable causing an error too? and what is the meaning of this member variable?
我通过CodeBlocks 8.02使用gcc版本3.4.5(mingw-vista special)。
I'm using gcc version 3.4.5 (mingw-vista special) through CodeBlocks 8.02.
在Visual Studio Express 2008 - Microsoft(R)C / C ++ Optimizing Compiler 15.00.30729.01 for 80x86,我收到以下消息:
On Visual Studio Express 2008 - Microsoft(R) C/C++ Optimizing Compiler 15.00.30729.01 for 80x86, I got the following messages:
class Foo {
int a[]; // warning C4200: nonstandard extension used : zero-sized array in struct/union - Cannot generate copy-ctor or copy-assignment operator when UDT contains a zero-sized array
};
int a[];
void bar() {
int a[]; // error C2133: 'a' : unknown size
}
解释。
推荐答案
C99支持一个叫做柔性数组成员的东西,它被允许作为结构体的最后一个成员。当你动态分配这样的结构时,你可以增加 malloc()
请求的数量,以提供数组的内存。
C99 supports something called a 'flexible' array member that is allowed to be the last member of a struct. When you dynamically allocate such a struct you can increase the amount requested from malloc()
to provide for memory for the array.
有些编译器将它添加为C90和/或C ++的扩展。
Some compilers add this as an extension to C90 and/or C++.
因此,您可以使用如下代码:
So you can have code like the following:
struct foo_t {
int x;
char buf[];
};
void use_foo(size_t bufSize)
{
struct foo_t* p = malloc( sizeof( struct foo_t) + bufSize);
int i;
for (i = 0; i < bufSize; ++i) {
p->buf[i] = i;
}
}
成员直接(作为本地或全局/静态变量),因为编译器不知道要为其分配多少内存。
You can't define a struct with a flexible array member directly (as a local or a global/static variable) as the compiler won't know how much memory to allocate for it.
我真的不知道你会很容易使用这样的事情与C ++的新
运算符 - 我想你必须分配内存的对象使用 malloc()
并使用 new
。也许一些类/结构体特定的 operator new
可以使用...
I'm honestly not sure how you'd easily use such a thing with C++'s new
operator - I think you'd have to allocate the memory for the object using malloc()
and use placement new
. Maybe some class/struct specific overload of operator new
could be used...
这篇关于静态数组定义为未指定大小,空括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!