给定飞机上的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/

10-15 02:14