logo

C 구조체 배열

구조체 배열을 사용하는 이유는 무엇입니까?

5명의 학생 데이터를 저장해야 하는 경우를 생각해 보세요. 아래와 같은 구조를 사용하여 저장할 수 있습니다.

 #include struct student { char name[20]; int id; float marks; }; void main() { struct student s1,s2,s3; int dummy; printf('Enter the name, id, and marks of student 1 '); scanf('%s %d %f',s1.name,&s1.id,&s1.marks); scanf('%c',&dummy); printf('Enter the name, id, and marks of student 2 '); scanf('%s %d %f',s2.name,&s2.id,&s2.marks); scanf('%c',&dummy); printf('Enter the name, id, and marks of student 3 '); scanf('%s %d %f',s3.name,&s3.id,&s3.marks); scanf('%c',&dummy); printf('Printing the details....
'); printf('%s %d %f
',s1.name,s1.id,s1.marks); printf('%s %d %f
',s2.name,s2.id,s2.marks); printf('%s %d %f
',s3.name,s3.id,s3.marks); } 

산출

 Enter the name, id, and marks of student 1 James 90 90 Enter the name, id, and marks of student 2 Adoms 90 90 Enter the name, id, and marks of student 3 Nick 90 90 Printing the details.... James 90 90.000000 Adoms 90 90.000000 Nick 90 90.000000 

위 프로그램에서는 구조에 학생 3명의 데이터를 저장했습니다. 그러나 학생 수가 20명인 경우 프로그램의 복잡성이 증가합니다. 이 경우 20개의 서로 다른 구조 변수를 선언하고 하나씩 저장해야 합니다. 학생을 추가할 때마다 변수를 선언해야 하기 때문에 이는 항상 어려울 것입니다. 모든 변수의 이름을 기억하는 것도 매우 까다로운 작업입니다. 그러나 c를 사용하면 다양한 구조 변수를 선언하는 것을 피할 수 있는 구조 배열을 선언할 수 있습니다. 대신 다양한 엔터티의 정보를 저장하는 모든 구조를 포함하는 컬렉션을 만들 수 있습니다.

C의 구조 배열

구조체의 배열 각 변수에는 서로 다른 엔터티에 대한 정보가 포함되어 있는 여러 구조 변수의 모음으로 정의할 수 있습니다. 배열 C의 구조 다양한 데이터 유형의 여러 엔터티에 대한 정보를 저장하는 데 사용됩니다. 구조체 배열은 구조체 컬렉션이라고도 합니다.

c 구조체 배열

5명의 학생 정보를 저장하고 인쇄하는 구조체 배열의 예를 살펴보겠습니다.

 #include #include struct student{ int rollno; char name[10]; }; int main(){ int i; struct student st[5]; printf(&apos;Enter Records of 5 students&apos;); for(i=0;i<5;i++){ printf('
enter rollno:'); scanf('%d',&st[i].rollno); name:'); scanf('%s',&st[i].name); } printf('
student information list:'); for(i="0;i&lt;5;i++){" printf('
rollno:%d, name:%s',st[i].rollno,st[i].name); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Enter Records of 5 students Enter Rollno:1 Enter Name:Sonoo Enter Rollno:2 Enter Name:Ratan Enter Rollno:3 Enter Name:Vimal Enter Rollno:4 Enter Name:James Enter Rollno:5 Enter Name:Sarfraz Student Information List: Rollno:1, Name:Sonoo Rollno:2, Name:Ratan Rollno:3, Name:Vimal Rollno:4, Name:James Rollno:5, Name:Sarfraz </pre> <hr></5;i++){>