c - C中二维动态数组查找点

标签 c arrays multidimensional-array

给定平面上的 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;
}

最佳答案

试试这个

#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;
}

关于c - C中二维动态数组查找点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30829855/

相关文章:

javascript - 比较 JavaScript 数组

javascript - 到达数组末尾后如何执行函数?

python - 将图像另存为numpy数组

python - 将1D字节对象 reshape 为3D numpy数组

php - 将多次访问的具有常量值的数组放在哪里?

c++ - 将字符长度从数组复制到 std::string

c - C中函数的返回值

c - 初始化结构段错误

c - 使用memcpy方法

无法使用 gcc-7 编译