gpt4 book ai didi

c - 输出以一种奇怪的方式排序

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:10 24 4
gpt4 key购买 nike

我写了下面的代码,但从输出中可以看出有问题。我可能犯了一个指针错误。你能帮忙吗?

未排序的名称:

纽约乔治亚州波士顿

排序名称:

仓鼠乔治亚州纽永

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 3

void sort(char x[3][100]);
void swap(char **, char **);

int i,j;
char names[SIZE][100];
char *temp;

int main(void){

//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < SIZE; i++)
{
fgets( names[i], 99, stdin );
}
//print entered names
puts("\nUnsorted Names:\n");
for (i = 0; i < SIZE; i++)
{
printf("%s", names[i]);
}

sort(names);

//print sorted names
puts("\nSorted Names:\n");
for (i = 0; i < SIZE; i++)
{
printf("%s", names[i]);
}

getch();
}

//sorting function
void sort(char angut[3][100]){

for (i = 0; i < SIZE-1; i++)
{
for (j = i+1; j < SIZE; j++)
{
if (strcmp( angut[i], angut[j] ) >0)
{
swap(&angut[i],&angut[j]);
}

}

}

}

//swapping function
void swap(char **first, char **second){

temp=*second;
*second=*first;
*first=temp;

}

最佳答案

您处于未定义行为的领域。让我们使用真正的编译器(例如 gcc)编译您的代码。这是(相关的)输出:

a.c: In function 'sort':
a.c:50:13: warning: passing argument 1 of 'swap' from incompatible pointer type [enabled by default]
a.c:8:6: note: expected 'char **' but argument is of type 'char (*)[100]'
a.c:50:13: warning: passing argument 2 of 'swap' from incompatible pointer type [enabled by default]
a.c:8:6: note: expected 'char **' but argument is of type 'char (*)[100]'

如您所见,您为 swap 提供了错误的参数。为什么这个论点不好?原因如下:

angut 是一个二维数组,实际上它只是一个分成几行的数组。 angut[i] 是该数组的一行。请注意,这不是指针,它实际上是 char [100] 类型的数组的整行。 (旁注:如果将它传递给函数,它会衰减为指针)。现在您正在获取它的地址,即该数组中一行的地址,类型为 char (*)[100]

现在这是一个您正试图传递给 swap 的指针。但是等等,这不是指向指针(指向 char)的指针,它是指向数组一行的指针。这就是不兼容性的来源,这就是您得到错误结果的原因。


这应该足以解决您的问题,但下面是发生的事情,因此会出现奇怪的结果。让我们看一个 char **:

+----------+        +----------+        +----------+
| char **a | ----> | char *b | ----> | char c |
+----------+ +----------+ +----------+

通过更改*a,您将更改b。现在让我们看看您实际发送给该函数的内容:

+----------------+        +--------------+
| char (*a)[100] | ----> | char b[100] |
+----------------+ +--------------+

所以现在改变 *a 实际上改变了 b,这是你的数据,而不是指向你的数据的指针。 swap 函数不知道这一点,所以它认为 a 是一个 char **。那么 swap 认为 *a 的意思是指向某个字符串的指针,对吧?你实际上给它的是字符串本身。

因此,当您执行 *a1 = *a2; 时,编译器从 a2 指向的位置获取 4 个字节(在您的体系结构中)并将其写入来自的 4 个字节a1 指向.

你看到发生了什么吗?基本上,您的字符串的前四个字节被交换,作为指针构成。这就是为什么您会看到 BostorkNewyon 前四个字符被交换的原因。

关于c - 输出以一种奇怪的方式排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18984713/

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