简体   繁体   English

一次在多维数组中编写字符串C

[英]Writing a string in a multidimensional array at once C

Let's say I have a multidimensional array : 假设我有一个多维数组:

char myArray[3][15]={
"foofoofoo\0",
"barfoofoo\0",
"foobarfoo\0"};

Do I have to run a loop to set new strings in myArray, or is there any way to do this in C: 我是否需要运行循环以在myArray中设置新的字符串,或者是否有任何方法可以在C中执行此操作:

myArray[][]={
"secondChain\0",
"newChain\0",
"foofoofoo\0"};

I'm quite new to the magic world of code, so please excuse my question if it's dumb! 我对神奇的代码世界还很陌生,所以请问我的问题是否愚蠢!

If you've got C99 with support for compound literals, you don't have to write the loop in your code (you can use a single call to memset() to do the job, which hides the loop inside the function): 如果您拥有支持复合文字的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;
}

The extra parentheses around the compound literal ((char[3][15]){"secondChain", "newChain", "foofoofoo"}) are necessary with the library I use (on Mac OS X 10.8.5 with GCC 4.8.1) because there's a macro definition for memcpy() and the commas in the compound literal confuse the C preprocessor if they are not enclosed in a set of parentheses: 我使用的库(在Mac OS X 10.8.5和GCC 4.8上((char[3][15]){"secondChain", "newChain", "foofoofoo"})的复合文字((char[3][15]){"secondChain", "newChain", "foofoofoo"})的多余括号是必需的。 1)因为存在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));

Nominally, they are unnecessary. 从名义上讲,它们是不必要的。 If it was written: 如果是这样写的:

(memcpy)(myArray, (char[3][15]){"secondChain", "newChain", "foofoofoo"}, sizeof(myArray));

it would be OK because that is not an invocation of the function-like memcpy() macro. 可以,因为那不是对类似函数的memcpy()宏的调用。

#include <stdio.h>

int main(){

    char myArray[3][15]= {"foofoofoo", "barfoofoo", "foobarfoo"};

    //Set New values here
    strcpy(myArray[0], "Test1");
    strcpy(myArray[1], "Test2");
    strcpy(myArray[2], "Test3");

    printf("%s, %s, %s", myArray[0], myArray[1], myArray[2]);

    return 0;
}

Output: 输出:

Test1, Test2, Test3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM