【问题标题】:Writing a string in a multidimensional array at once C一次在多维数组中写入一个字符串 C
【发布时间】:2013-10-21 07:15:50
【问题描述】:

假设我有一个多维数组:

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

我是否必须运行一个循环来在 myArray 中设置新字符串,或者有什么方法可以在 C 中做到这一点:

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

我对神奇的代码世界还很陌生,所以如果我的问题很愚蠢,请原谅我的问题!

【问题讨论】:

标签: c string multidimensional-array


【解决方案1】:

如果您的 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() 宏。

【讨论】:

    【解决方案2】:
    #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;
    }
    

    输出:

    Test1, Test2, Test3
    

    【讨论】:

    • 使用 strncpy 这样就不会有数组末尾运行的危险。
    • strncpy() 的问题在于,如果要复制的字符串太长,则存在数组不会被空终止的危险。这是一个非常奇怪的功能;如果你说数组长 15 个字节,它总是写入 15 个字节(如果你说它是 20 KiB,它会写入 20 KiB,即使源字符串只有 5 个字符长),必要时使用空填充,而不是空如果源字符串过长则终止。小心——非常小心。
    • ISO/IEC 9899:2011:§7.24.2.4 strncpy 函数:strncpy 函数复制的字符不超过n(不复制空字符后的字符)从s2 指向的数组到s1.308 指向的数组) […] 如果s2 指向的数组是一个比n 字符短的字符串,则将空字符附加到s1 指向的数组中的副本,直到全部写入 n 字符。308) 因此,如果在第一个 n 字符中没有空字符s2指向的数组,结果不会以null结尾。
    • @JonathanLeffler 是的,我知道这一点。但是在你编辑你的评论之前,我不清楚你所说的'如果你说数组长 15 个字节,它总是写 15 个字节(如果你说它是 20 KiB,它写 20 KiB,即使源字符串只有 5 个字符长)'。认为这是一个错字,因为这个答案的代码中没有strncpy() :)
    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多