将字符串从一个结构复制到另一个结构

标签 c arrays string structure

我正在尝试编写一个程序,按字母顺序对一本小词典进行排序。为此,我需要能够将字符串从未排序的字典复制到已排序的字典。如果我尝试这样复制整个字符串:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

struct entry
{
    char word[15];
    char definition[50];
};


void dictionarySort(struct entry dictionary[]) {
    int i;

    struct entry dictionary2[100] = {{}};

    for (i = 0; i <= strlen(&dictionary->word[0]); i++) {
        dictionary2[0].word[i] = dictionary[0].word[i];

    }
    dictionary2[0].word = dictionary[0].word;

    printf("%s\n",dictionary2[0].word);

}

int main (void) {
    struct entry dictionary[100] = 
    {{"aerie", "a high nest"},
    {"abyss", "a bottomless pit"},
    {"ahoy", "a nautical call of greeting"},
    {"addle", "to become confused"},
    {"aardvark", "a burrowing African mammal"},
    {"agar", "a jelly made of seaweed"},
    {"acumen", "mentally sharp; keen"},
    {"aigrette", "an ornamental cluster of feathers"},
    {"affix", "to attach"},
    {"ajar", "partially opened"}};
    dictionarySort(dictionary);
}

我收到以下错误消息:

error: array type 'char [15]' is not assignable
        dictionary2[0].word = dictionary[0].word;
        ~~~~~~~~~~~~~~~~~~~ ^

另一方面,如果我复制单个字符,我无法区分字符串,而这在访问 dictionary2 时是必需的。

最佳答案

正如您的编译器告诉您数组在 c 中不可赋值,要复制字符串您需要 strcpy() 函数

strcpy(dictionary2[0].word[i], dictionary[0].word[i]);

您需要确保目标数组有足够的空间来容纳字符串,即字符串 +1 中以 nul 终止符的字符数。

关于将字符串从一个结构复制到另一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724953/

相关文章:

python - 将看起来像列表的字符串转换为真正的列表 - python

c - 如何清除 UNIX 系统上 tty 输入队列中的未读数据?

c - 如何使用 gimp_drawable_set_pixel()?

c - 在 C 中调整二维数组大小时遇到​​问题

在 X-Macro 中打印数组元素时出现编译错误

c - 将数组分配给不同的变量

c - 如何在 C 中为未知长度的字符串数组分配内存

c# - 在 C# 中编码(marshal) IntPtr 数组

javascript - aurelia View 中的过滤器数组

javascript - R 中 Shiny 的 STRING 交互网络