我正在学习C语言。我有一个方法,它需要3个字符串,并将它们组合起来进行某些操作。以下是我的第一次实现,使用GCC编译器。
void foo(const char *p1, const char *p2, const char *p3)
{
size_t length = strlen(p1) + strlen(p2) + strlen(p3);
char combined[length + 1];
memset(combined, 0, length + 1);
strcat(combined, p1);
strcat(combined, p2);
strcat(combined, p3);
printf("Result : %s", combined);
}
int main()
{
foo("hello ", "world ", "how");
return 0;
}
这个代码运行得很好。但是当我使用cc -Wall -pedantic -g foo.c -o foo
编译时,出现了警告,例如ISO C90 forbids variable length array ‘combined’
。MSVC不能编译这段代码。修改代码如下:
void foo(const char *p1, const char *p2, const char *p3)
{
size_t length = strlen(p1) + strlen(p2) + strlen(p3);
char *combined = (char *) malloc(length + 1);
memset(combined, 0, length + 1);
strcat(combined, p1);
strcat(combined, p2);
strcat(combined, p3);
printf("Result : %s", combined);
free(combined);
}
问题
- 这是正确的实现吗?
- 如果可变长度数组不是标准的一部分,为什么GCC实现了它?如果代码只预计在GCC上编译,使用可变数组比使用malloc更好吗?
- 我认为经验法则是,如果所需内存在编译时已知,请使用数组,否则请使用malloc来分配所需内存。这正确吗?
- 我的代码预计将在GCC和MSVC上编译。我通常会在GCC上开发。那么,有哪些编译器标志可以确保最大的可移植性?目前,我正在使用
-Wall -pedantic
。我应该也使用-ansi
吗?在MSVC中有哪些等效的标志可用? - 编写可移植C代码时需要考虑的其他常见事项有哪些?
calloc
进行分配,要么通过将combined [0] =' \ 0'
分配来避免memset
。这对于第一个strcat
正常工作已足够。 - Jens Gustedtvoid *
的库函数。只需使用char *combined = malloc(length + 1);
。此外,您需要检查malloc()
的返回值。顺便说一下,在这种情况下,snprintf()
更好,我个人认为。 - guestprintf
,那么你的代码非常低效。只需使用三个%s
格式说明符。我知道这可能只是一个示例,但我见过可怕的代码(例如在svn
客户端中),它确切地做到了这一点 - 在想要显示它们到stdout
的所有信息字符串时,跳过了一个巨大的迷宫,动态分配和连接它们。 - R.. GitHub STOP HELPING ICE