gpt4 book ai didi

c - 城市名称排序失败

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:25 26 4
gpt4 key购买 nike

我想对输入的城市名称进行排序,但下面的代码给了我这样的信息:

输入:

NewyorkGeorgetownBerlin

Output:

BerlinGewyorkBeorgetown

Why is that? I was thinking to compare with strcmp and swap the pointers then but it seeems it is not working.

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

void sort(char *dummy);
void swap(char *first, char *second);

int i;
char *names[3];
char *temp;

int main(void) {
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
names[i]=malloc(100);
fgets( names[i], 99, stdin);
}

//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}

sort(names);

//print sorted names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}

getch();
}

//sorting function
void sort(char *dummy)
{
for (i = 0; i &lt; 2; i++) {
if (strcmp( &dummy[i], &dummy[i+1]) > 0) {
swap(&dummy[i], &dummy[i+1]);
}
}
}

//swapping function
void swap(char *first, char *second)
{
temp=second;
second=first;
first=temp;
}

最佳答案

当您将 swap 调用为

swap(&dummy[i], &dummy[i+1]);

您对 address-of 运算符的使用实际上生成了一个指向 char 的指针。但是 swap 函数需要一个指向 char 的指针,这使得 swap 中指针的使用成为未定义的行为。

swap 函数更改为将指针到指针作为参数并使用取消引用运算符 *,它应该会更好地工作:

void swap(char **first, char **second)
{
char *tmp = *first;
*first = *second;
*second = tmp;
}

另一个问题是您在调用 strcmp 时也在指针上使用地址运算符。在那种情况下,您不应该这样做。

第三个问题是您将一个指针数组传递给仅接受一个char 指针的sort 函数。将原型(prototype)(和函数)更改为

void sort(char *dummy[]);

令人惊讶的是,它甚至可以为您编译所有这些问题。如果不是错误,至少您应该收到大量警告。

关于c - 城市名称排序失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18891053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com