【发布时间】:2016-05-01 10:32:44
【问题描述】:
- 程序需要根据每个单独结构的 zip 元素从最小到最大对结构进行排序。
- 输入基于输入/输出重定向。 input.txt 文件的示例如下:
Jason Solis 20294 Lorenzana Dr Woodland Hills, CA 91364 Robert Smith 19831 Henshaw St Culver City, CA 94023 Bob Arum 5142 Dumont Pl Azusa, CA 91112
代码:
struct info {
char name[BUFF_SIZE];
char stAddress[BUFF_SIZE];
char cityAndState[BUFF_SIZE];
char zip[BUFF_SIZE];
};
void selectionSort(struct info *ptrStruct);
int main(void)
{
int count;
char buffer[600];
struct info *ptrStruct[512];
for (count = 0; count < 18; count++)
{
ptrStruct[count] = (struct info*) malloc(sizeof(struct info));
gets(buffer);
strcpy(ptrStruct[count]->name, buffer);
gets(buffer);
strcpy(ptrStruct[count]->stAddress, buffer);
gets(buffer);
strcpy(ptrStruct[count]->cityAndState, buffer);
gets(buffer);
strcpy(ptrStruct[count]->zip, buffer);
}
selectionSort(ptrStruct);
printf("\n\nLEAST TO GREATEST\n");
for (count = 0; count < 18; count++)
{
printf("%s\n", ptrStruct[count]->name);
printf("%s\n", ptrStruct[count]->stAddress);
printf("%s\n", ptrStruct[count]->cityAndState);
printf("%s\n", ptrStruct[count]->zip);
}
}
void selectionSort(struct info *ptrStruct[])
{
int count2;
int count1;
int minIndex;
struct info *ptrTemporary;
for (count2 = 0; count2 < 18 - 1; count2++)
{
minIndex = count2;
for (count1 = count2 + 1; count1 < 18; count1++)
{
if (strcmp(ptrStruct[count1]->zip, ptrStruct[minIndex]->zip) < 0)
minIndex = count1;
}
ptrTemporary = ptrStruct[count2];
ptrStruct[count2] = ptrStruct[minIndex];
ptrStruct[minIndex] = ptrTemporary;
}
}
【问题讨论】:
-
什么是
STRUCT_SIZE? -
访问元素,然后对它们进行排序
-
STRUCT_SIZE 我刚改成 512。
-
@RodEfraim:胡,18 岁就可以了,不是吗?
-
好的,最后:这是错误
selectionSort(ptrStruct);这个调用应该会让编译器痛苦地大喊。
标签: c sorting pointers data-structures struct