如果我们比较整数,我们会将其中一个指定为最大/最小的整数。 但是,当我尝试比较两个以上的字符串时,我无法管理分配。 在我的代码" for loop"比较两个字符串。这是一个很好的方法,但我需要将其中一个单独地与其他方法进行比较。 (我可以预测我需要使用两个for循环,但我也无法实现)你的建议是什么?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct wordSorting
{
char name[15];
int i = 0;
};
int main()
{
wordSorting *wordElement = (wordSorting *)malloc(sizeof(wordSorting));
wordElement = (wordSorting *)malloc(sizeof(wordSorting));
printf("-- Enter three person name --\n\n");
for (wordElement->i = 0; wordElement->i < 3; wordElement->i++)
{
printf("Enter %d. person name: ", wordElement->i + 1);
scanf("%s", wordElement[wordElement->i].name);
}
printf("\n");
for (wordElement->i = 0; wordElement->i < 3; wordElement->i++)
{
if ((strcmp(wordElement[wordElement->i].name, wordElement[wordElement->i + 1].name))<0)
{
printf("%s", wordElement[wordElement->i].name);
}
}
}
答案 0 :(得分:0)
<强>第一强>
options["restore-path"] = "/path/to/restore"
无法启动typedef / struct的成员。 这不是定义typedef的方法,将其更改为:
typedef struct wordSorting
{
char name[15];
int i = 0;
};
<强>第二强>
typedef struct
{
char name[15];
int i;
}wordSorting;
毫无意义。 malloc返回void指针,你已经在第一行代码的第一个元素处初始化了你的变量。 并且,正如有人编辑:请不要投出malloc返回。
第三,:
wordElement = (wordSorting *)malloc(sizeof(wordSorting));
您正在为一个元素分配空间,没有定义数组,那么wordSorting *wordElement = (wordSorting *)malloc(sizeof(wordSorting));
wordElement = (wordSorting *)malloc(sizeof(wordSorting));
printf("-- Enter three person name --\n\n");
for (wordElement->i = 0; wordElement->i < 3; wordElement->i++)
{
printf("Enter %d. person name: ", wordElement->i + 1);
scanf("%s", wordElement[wordElement->i].name);
}
是未定义的行为。
<强>最后强>
我不知道你使用的是什么编译器,但是gcc无法编译这么多错误的代码......
<强>建议。强>
我认为你需要的是使用数组,但你必须通过以下方式分配你需要的成员数量:
wordElement[wordElement->i].name
或简单地说,使用本地数组:
wordSorting *wordElement = malloc(sizeof(wordSorting)*num_of_elements);