如何仅用指针在void函数中同步排序点结构体与对应距离?
问题分析与修复方案
你的代码存在三个核心问题,导致同时排序点和距离时失效:
1. 函数声明、定义与调用不匹配
- 原代码中
sort函数声明为void sort();,但定义时要求传入float *d和struct point *p两个参数,调用时却只传了d,参数传递混乱直接引发未定义行为。 - 必须同步修改声明、定义和调用,把两个必要参数都传进去。
2. 错误使用sizeof计算数组长度
- 在函数内部,指针
d的sizeof结果是指针本身的字节数(比如64位系统是8字节),不是数组的总长度。必须把数组元素个数n作为第三个参数传入sort函数,才能正确控制排序循环的边界。
3. 排序逻辑的索引错误
- 原冒泡排序的内层循环和元素比较逻辑有误,
j的起始值和比较对象的索引搭配错误,会导致部分元素无法正确比较交换。
修正后的完整代码
#include <stdio.h> #include <math.h> struct point { float x, y; }; // 同步修改函数声明,加入必要参数 void sort(float *d, struct point *p, int n); int main() { int n; printf("Enter the number of points in the system:"); scanf("%d", &n); float d[n], xi, yi; struct point p[n]; printf("\nEnter the X and Y coordinates of the points-\n"); for (int i = 0; i < n; i++) { printf("Enter the X coordinate of point %d: ", i + 1); scanf("%f", &p[i].x); printf("Enter the Y coordinate of point %d: ", i + 1); scanf("%f", &p[i].y); } printf("\nPoints entered are-\n"); for (int i = 0; i < n; i++) { printf("%d- (%0.2f,%0.2f)\n", i + 1, p[i].x, p[i].y); } printf("\nEnter the X coordinate of point from which distance is to be calculated:"); scanf("%f", &xi); printf("Enter the Y coordinate of point from which distance is to be calculated:"); scanf("%f", &yi); for (int i = 0; i < n; i++) { // sqrt结果非负,fabs可以省略 d[i] = sqrt(pow(p[i].x - xi, 2) + pow(p[i].y - yi, 2)); } printf("\nDistance- "); for (int i = 0; i < n; i++) { printf("%0.2f ", d[i]); } printf("\n"); // 调用时传入三个参数:距离数组、点数组、元素个数 sort(d, p, n); printf("\n\nSorted distance- "); for (int i = 0; i < n; i++) { printf("%0.2f ", d[i]); } printf("\n\nSorted points-\n"); for (int i = 0; i < n; i++) { printf("%d- (%0.2f,%0.2f)\n", i + 1, p[i].x, p[i].y); } } // 加入n参数,修正排序逻辑 void sort(float *d, struct point *p, int n) { // 标准冒泡排序实现,全程用指针操作元素 for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { // 指针偏移访问元素:*(d+j) 等价于 d[j] if (*(d + j) > *(d + j + 1)) { // 交换距离 float temp = *(d + j); *(d + j) = *(d + j + 1); *(d + j + 1) = temp; // 交换对应点的坐标,指针访问结构体成员 float px_temp = (p + j)->x; float py_temp = (p + j)->y; (p + j)->x = (p + j + 1)->x; (p + j)->y = (p + j + 1)->y; (p + j + 1)->x = px_temp; (p + j + 1)->y = py_temp; } } } }
修改说明
- 参数同步:更新
sort函数的声明、定义和调用,确保传入距离数组、点数组和元素个数三个参数。 - 数组长度传递:用
n代替sizeof计算循环边界,彻底解决指针无法获取数组长度的问题。 - 排序逻辑修正:改为标准冒泡排序的相邻元素比较逻辑,确保所有元素都能正确参与排序。
- 指针操作优化:全程用指针偏移(
*(d+j)、(p+j)->x)访问元素,符合纯指针实现的要求。
测试你的输入用例,修正后的代码会输出:
Enter the number of points in the system:2 Enter the X and Y coordinates of the points- Enter the X coordinate of point 1: 5 Enter the Y coordinate of point 1: 6 Enter the X coordinate of point 2: 3 Enter the Y coordinate of point 2: 4 Points entered are- 1- (5.00,6.00) 2- (3.00,4.00) Enter the X coordinate of point from which distance is to be calculated:0 Enter the Y coordinate of point from which distance is to be calculated:0 Distance- 7.81 5.00 Sorted distance- 5.00 7.81 Sorted points- 1- (3.00,4.00) 2- (5.00,6.00)
内容的提问来源于stack exchange,提问作者Ashutosh Yadav
相关产品推荐
相关产品推荐

