What's the difference between (1)
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char s2[strlen(s) + 1];
strcpy(s2, s);
并且(2)
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char *s2 = malloc(strlen(s) + 1);
strcpy(s2, s);
在什么情况下应该使用它们中的每一个?当你确定数组
char s2[strlen(s) + 1];
s2
是一个数组。在第二种情况下,
char *s2 = malloc(strlen(s) + 1);
s2
是一个指针。
顺便提一下,如果编译器不支持VLA,第一种方法将无法工作。
根据最新标准C11
,VLA是一个可选的特性,编译器不必支持。第二种方法是C标准库的一个组成部分,无需任何额外的编译器支持即可使用。
void func (int x, int y, int array[x][y]) {}
,其中array
实际上是一个指针,而不是数组。
sizeof(s)
而不是strlen。strlen
调用。 - M.Mstatic char s[5]; char s2[strlen(s)];
。我们成功创建了一个零长度数组。在gcc中编译得很好。 - Lundinstrlen(s) + 1
,它不可能计算为零。 - M.M
free()
它。祝愉快! :) - Sourav GhoshC99
之前不太可能支持 VLA(我没有考虑 GCC 扩展)。如果我有任何错误,请您指正。 - Sourav Ghosh