如果您的 C99 支持复合文字,则不必在代码中编写循环(您可以使用对 memset() 的单个调用来完成这项工作,这会将循环隐藏在函数内):
#include <stdio.h>
#include <string.h>
int main(void)
{
char myArray[3][15] = {"foofoofoo", "barfoofoo", "foobarfoo"};
printf("Before: %s %s %s\n", myArray[0], myArray[1], myArray[2]);
memcpy(myArray, ((char[3][15]){"secondChain", "newChain", "foofoofoo"}), sizeof(myArray));
printf("After: %s %s %s\n", myArray[0], myArray[1], myArray[2]);
return 0;
}
复合文字 ((char[3][15]){"secondChain", "newChain", "foofoofoo"}) 周围的额外括号对于我使用的库是必需的(在带有 GCC 4.8.1 的 Mac OS X 10.8.5 上)因为 memcpy() 的宏定义和复合文字中的逗号如果它们没有包含在一组括号中,则会混淆 C 预处理器:
mass.c: In function ‘main’:
mass.c:9:91: error: macro "memcpy" passed 5 arguments, but takes just 3
memcpy(myArray, (char[3][15]){"secondChain", "newChain", "foofoofoo"}, sizeof(myArray));
名义上,它们是不必要的。如果是这样写的:
(memcpy)(myArray, (char[3][15]){"secondChain", "newChain", "foofoofoo"}, sizeof(myArray));
没关系,因为这不是调用类似函数的memcpy() 宏。