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