【问题标题】:Find point with two-dimensional dynamic array in C在C中用二维动态数组查找点
【发布时间】:2023-03-16 20:38:01
【问题描述】:

给定平面上的 m 个点。 xy 坐标的数量必须是 通过键盘输入。如何从 xy 找到这个坐标?带二维动态数组。

现在我有了这个,但它不起作用:

int **enterPoints (int m) {
    int i, **points;
    scanf("%d",&m);
    points = (int **)malloc(m*sizeof(int *));
    if (points != NULL) {
        for (i=0; i<m; i++) {
            *(points+i) = (int *)malloc(m*sizeof(int));
            if (*(points+i)==NULL)
                break;
        }
        {
            printf("enter %d points coord X and Y:", i+1);
            scanf("%d %d", &*(*(points+i)+0), &*(*(points+i)+1));
            *(*(points+i)+2)=0;
        }
    }
    free(points);
    return points;
}

【问题讨论】:

  • 什么不起作用?不是在编译吗?它给出错误的结果吗?你的实际问题是什么? “如何从 xy 中找到这个坐标?”是什么意思?
  • 一般来说论坛是Value = *(ArrayStartingPoint + ((x*y.Length+y)*sizeof(array type)))
  • 感谢我希望使用的类似公式。我无法输入 x 和 y 的数字。现在我无法运行该程序......而且不明白为什么。它不会做任何事情,我点击运行并构建并且没有任何反应。我是 C 编程的初学者...
  • 您需要学习格式化您的代码,使其易于阅读和理解。你所拥有的格式非常糟糕。您不想在返回指针之前free(points);。您的第二个malloc() 正在浪费空间。如果我指定 1 个坐标,它不会分配足够的空间;如果我指定 1,000,000 个坐标,它会尝试在一百万个分配过程中分配一百万个整数(大多数机器没有那么多内存 - 需要 4 TiB)。 m 应该是 2
  • 我觉得自己是格式化的英雄。

标签: c arrays multidimensional-array


【解决方案1】:

试试这个

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

int **enterPoints (int m){
    int i, **points;
    //scanf("%d",&m);//already get as argument
    if(m<=0)
        return NULL;
    points = (int**)malloc(m*sizeof(int*));
    if (points != NULL){
        for (i=0; i<m; i++){
            points[i] = (int*)malloc(2*sizeof(int));
            if(points[i]!=NULL){
                printf("enter %d points coord X and Y:", i+1);fflush(stdout);
                scanf("%d %d", &points[i][0],&points[i][1]);
            }
        }
    }
    //free(points);//free'd regions is unusable
    return points;
}

int main(void){
    //test code
    int i, m, **points;
    //scanf("%d", &m);
    m = 3;
    points = enterPoints(m);
    for(i = 0; i < m; ++i){
        printf("(%d, %d)\n", points[i][0], points[i][1]);
        free(points[i]);
    }
    free(points);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 2011-01-11
    • 2014-02-27
    • 1970-01-01
    • 2020-05-20
    • 2013-11-14
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多