簡體   English   中英

c掃描2D陣列

[英]c scaning for 2D arrays

我對C語言很陌生,遇到了一個問題,我認為它與指針有某種關系(可能是錯誤的)。第一個輸入顯然是輸入的數量,它(當前)還確定數組的寬度和高度。 接下來的幾個輸入應該讀取我自己的數組坐標和值。 在最后一點上,我試圖打印出數組。 流產是非常非常錯誤的。 關於我在哪里做錯的任何提示掃描的部分或打印的部分,或兩者都有?

(如果st_objects是5,x_cord和y_cord的最大輸入是4)我只想將一些值更改為0以外的值。首先我需要用0值填充數組嗎?

就像是:

0 0 0 2 0

0 2 3 0 0

0 0 0 0 2

0 0 0 1 2

0 0 2 0 3

ps:使用getchar函數作為輸入會更好嗎?

我的代碼是:

 #include <stdio.h>

int main(){
  int st_objects;
  scanf("%d",&st_objects);

  int x_cord;
  int y_cord;
  int array[st_objects][st_objects];

  for(int i = 0; i < st_objects; i++){
    scanf("%d",&x_cord);
    scanf("%d",&y_cord);
    scanf("%d",&array[x_cord][y_cord]);

  }
  for(int i = 0; i < st_objects; i++){
    for(int j = 0; i < st_objects; j++){
      printf("%d",array[i][j]);
      }
     printf("\n");
   }

  return 0;
 }

您的掃描循環僅執行到st_object次(在本例中為5)。 因此,您只能輸入5個輸入。 但是,如果看到的話,該數組包含5 * 5 = 25個元素。 所以那是出錯的地方。

接下來,有更好的方法來掃描數組元素,像這樣

for(int i = 0; i < st_objects; i++)
   for(int j = 0; j < st_objects; j++)
         scanf("%d",&array[i][j]);

我認為您不完全了解二維數組及其元素的位置。

另一件事,您可能超出了矩陣邊界,因此請嘗試檢查x和y位置。

#include <stdio.h>

int main(){
              int st_objects;
              printf("Square Matrix length \n");

              scanf("%d",&st_objects);

              int x_cord;
              int y_cord;
              int array[st_objects][st_objects];

              for(int i = 0; i < st_objects*st_objects; i++){
              printf("x-position  \n");

             scanf("%d",&x_cord);
             printf("y-position   \n");

            scanf("%d",&y_cord);
            scanf("%d",&array[y_cord][x_cord]);

                                     }

      for(int i = 0; i < st_objects; i++){
           for(int j = 0; j < st_objects; j++){
                                printf("%d ",array[i][j]);
                                                   }
                 printf("\n");
                                }

          return 0;
       }

您的代碼中有2個錯誤。1)在第一個for循環中,i必須小於多維數組中元素的總數,即i <(st_objects * st_objects)。 2)for循環中的小錯誤。

    for(int j=0;j<st_objects;j++)

這是您的程序可以修改為的方式(適用於2x2):

    #include <stdio.h>
    int main(){
    int st_objects;
    scanf("%d",&st_objects);
    int x_cord;
    int y_cord;
    int array[st_objects][st_objects];
    for(int i = 0; i < (st_objects*st_objects); i++){
    printf("Enter x,y coordinate:\n");
    scanf("%d",&x_cord);
    scanf("%d",&y_cord);
    if(x_cord<st_objects&&y_cord<st_objects)
    {printf("Enter value at x,y:\n");
     scanf("%d",&array[x_cord][y_cord]);
    }else printf("\nWrong coordinate\n");
    }
    for(int i=0;i<st_objects;i++)
    {
     for(int j=0;j<st_objects;j++)
     {
      printf("%d\t",array[i][j]);
     }
     printf("\n");
    }

    return 0;
    }

我希望這有幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM