2015-06-14 16 views
0

給定平面中的m個點。通過鍵盤輸入的xy座標數必須爲 。如何從xy中找到這個座標?具有二維動態數組。查找具有二維動態數組的點C

現在我有這個,但它不工作:

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; 
} 
+2

什麼是不工作?它不是在編譯?它給出了錯誤的結果嗎?你的問題是什麼? 「如何從xy找到這個座標?」是什麼意思? – dingalapadum

+0

一般來說,forumla是'Value = *(ArrayStartingPoint +((x * y.Length + y)* sizeof(array type)))' –

+0

感謝一個公式,就像我希望使用的那樣。我無法輸入數字爲x和y。現在我無法運行程序...並不明白爲什麼。它不要做任何事情,我點擊運行和構建,沒有任何反應。我在編程...在編程... –

回答

0

試試這個

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