Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

อาร์เรย์หลายมิติในภาษา C คืออะไร?


อาร์เรย์คือกลุ่มของรายการที่เกี่ยวข้องกันซึ่งจัดเก็บด้วยชื่อสามัญ

ไวยากรณ์

ไวยากรณ์สำหรับการประกาศอาร์เรย์มีดังนี้ −

datatype array_name [size];

ประเภทของอาร์เรย์

Array แบ่งออกเป็น 3 ประเภทใหญ่ๆ ดังต่อไปนี้ −

  • อาร์เรย์หนึ่งมิติ
  • อาร์เรย์สองมิติ
  • อาร์เรย์หลายมิติ

การเริ่มต้น

อาร์เรย์สามารถเริ่มต้นได้สองวิธี มีการกล่าวถึงด้านล่าง −

  • คอมไพล์การเริ่มต้นเวลา
  • การเริ่มต้นรันไทม์

อาร์เรย์หลายมิติ

  • 'C' ช่วยให้อาร์เรย์มีมิติข้อมูลมากกว่า 3 (หรือ) มากขึ้น
  • ขีดจำกัดที่แน่นอนถูกกำหนดโดยคอมไพเลอร์

ไวยากรณ์

ไวยากรณ์มีดังนี้ −

datatype arrayname [size1] [size2] ----- [sizen];

ตัวอย่างเช่น

  • สำหรับอาร์เรย์ 3 มิติ −
    • int a[3] [3] [3];

จำนวนองค์ประกอบ =3*3*3 =27 องค์ประกอบ

โปรแกรม

ต่อไปนี้เป็นโปรแกรม C สำหรับอาร์เรย์หลายมิติ -

#include<stdio.h>
main ( ){
   int a[2][2] [2] = {1,2,3,4,5,6,7,8};
   int i,j,k;
   printf ("elements of the array are");
   for ( i=0; i<2; i++){
      for (j=0;j<2; j++){
         for (k=0;k<2; k++){
            printf("%d", a[i] [j] [k]);
         }
      }
   }
}

ผลลัพธ์

ผลลัพธ์ระบุไว้ด้านล่าง −

Elements of the array are :
1 2 3 4 5 6 7 8

พิจารณาอีกโปรแกรมหนึ่งสำหรับ Multi-Dimensional Array ในภาษาซีดังนี้ -

ตัวอย่าง

#include<stdio.h>
int main(){
   int tab, row, col;
   int students[3][3][2] = { { {1, 2}, {4, 5}},{ {2, 4}, {3, 5} },{ {7,8},{9,3}}};
   for (tab = 0; tab < 3; tab++){
      for (row = 0; row < 3; row++){
         for (col =0; col < 2; col++){
            printf("students[%d][%d][%d]= %d\n", tab, row, col,
            students[tab][row][col]);
         }
      }
   }
   return 0;
}

ผลลัพธ์

ผลลัพธ์ระบุไว้ด้านล่าง −

students[0][0][0]= 1
students[0][0][1]= 2
students[0][1][0]= 4
students[0][1][1]= 5
students[0][2][0]= 0
students[0][2][1]= 0
students[1][0][0]= 2
students[1][0][1]= 4
students[1][1][0]= 3
students[1][1][1]= 5
students[1][2][0]= 0
students[1][2][1]= 0
students[2][0][0]= 7
students[2][0][1]= 8
students[2][1][0]= 9
students[2][1][1]= 3
students[2][2][0]= 0
students[2][2][1]= 0