구조체 포인터, 구조체 배열 포인터. malloc을 이용한 구조체 (배열) 공간 할당받기
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct _employee
{
    char name[10];
    int  age;
    char company[20];
}employee;

int main (void)
{

    employee *em_p;
    em_p = (employee*)malloc(sizeof(employee)*3);
    //마지막에 *3이것만하면 배열되는거임?!! (ㅇㅇ)

    int i;

    for (i=0; i<3; i++)
    {
    printf("Input [%d]st employee's information\n", i+1);
    printf("name:");
    scanf("%s", em_p[i].name);
    printf("age:");
    scanf("%d", &em_p[i].age);
    printf("company:");
    scanf("%s", em_p[i].company);    
    }

    //sorting
    int j;
    char temp_name[10];
    int  temp_age;
    char temp_company[20];


    for ( i=0; i<3; i++)
   {   
       for ( j=0; j<3-(i+1); j++)
        {   
            if (strcmp(em_p[j].name, em_p[j+1].name) > 0 )
            {   
                strcpy (temp_name, em_p[j].name);
                temp_age =  em_p[j].age;
                strcpy (temp_company, em_p[j].company);

                strcpy (em_p[j].name, em_p[j+1].name);
                em_p[j].age = em_p[j+1].age;
                strcpy (em_p[j].company, em_p[j+1].company);
    
                strcpy (em_p[j+1].name, temp_name);
                em_p[j+1].age = temp_age;
                strcpy (em_p[j+1].company, temp_company);
             }   
        }   
    }   

    for (i=0; i<3; i++)
    {
    printf("\n====%dst employee's information ====\n", i+1);
    printf("name:%s\n", em_p[i].name);
    printf("age:%d\n", em_p[i].age);
    printf("company:%s\n", em_p[i].company);
    }
    return 0;


+ Recent posts