假设我有这个结构
typedef struct foo {
int a;
char b;
char *c;
} foo;
我想创建该结构的初始化实例
foo bar = { .a = 7 .b = 'x' .c = "hello" };
但是,如果我搞砸了并且忘记初始化我正在初始化的结构的元素之一怎么办......例如......
foo bar = { .a = 7, .c = "hello" };
...我只是忘记初始化元素“b”——在我给出的示例中很容易检测到这个错误,但对于更复杂的结构,尤其是正在开发的结构,这绝对是合理的.
有没有我可以传递给 gcc 的标志如果我犯了这样的错误,这会导致它生成警告吗?
最佳答案
使用“老派” ISO C 方式初始化结构(当不使用 -std=c99
编译时),gcc 默认会向您发出警告。除此之外,您需要设置的 gcc 标志是 -Wmissing-field-initializers
, 默认启用 AFAIK 这是 NOT 启用默认情况下,但作为 -Wextra
的一部分,正如 Michael Burr 在他的评论中所述,前提是您使用以下语法:
int main ( void )
{
foo bar = {123, "foobar"};//failed to init char b member
foo zar = {123, '\a'};//omitted c initialization
return 0;
}
这应该发出以下警告:
warning: initialization makes integer from pointer without a cast [enabled by default] foo bar = { 123, "foobar"}; warning: missing initializer for field ‘c’ of ‘foo’ [-Wmissing-field-initializers] foo zar = { 123, 'a'};
The major downside to this is, of course, that it makes your code harder to read, and maintain... not an insignificant down-side IMO...
If you can, and if the overhead isn't too bad, I'd simply write a function. Especially considering you have a char *
member field, which may require heap-allocated memory:
foo * init_foo(foo *str, int a, char b, char *c)
{
if (c == NULL) return NULL;// no char pointer passed
if (str == NULL) str = malloc(sizeof *str);//function allocates struct, too
str->a = a;
str->b = b;
str->c = calloc(strlen(c) + 1, sizeof *(str->c));//allocate char pointer
strcpy(str->c, c);
return str;
}
//optionally include custom free function:
void free_foo ( foo **f)
{
if ((*f)->c != NULL) free((*f)->c);
free(*f)
*f = NULL;//init pointer to NULL
}
这是最安全的方法...像这样调用这个函数:
foo *new_foo = init_foo( NULL, 123, '\a', "string");//allocate new struct, set all members
//free like so:
free_foo(&new_foo);//pass pointer to pointer
foo stack_foo;
init_foo(&stack_foo, 123, '\a', "string");//initialize given struct
//only free .c member
free(stack_foo.c);
stack_foo.c = NULL;
无论如何,在开发时,始终使用 -Wall
进行编译,并且为了安全起见,也使用 --pedantic
...
关于c - 如果我初始化一个结构但缺少一个元素,GCC 中是否有任何标志来警告我?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21671347/