[자료구조] 구조체 c

K근형·2023년 12월 11일
0

자료구조

목록 보기
3/12

구조체 c

#include <stdio.h>
#include <stdlib.h> // malloc, free, rand, srand

#pragma warning(disable : 4996)

typedef struct point
{
    int x;
    int y;
}point;

void input(point* p)
{
    printf("x좌표: ");
    scanf("%d", &p->x);

    printf("y좌표: ");
    scanf("%d", &p->y);
}

void output(point copy)
{
    printf("(%d, %d)\n", copy.x, copy.y);
}

int main(void)
{
    point p1, p2;

    /*p1.x = 10;
    p1.y = 20;

    p2.x = 100;
    p2.y = 200;*/

    printf("1번째 좌표 입력\n");
    input(&p1); //call by address : 전달하는 변수의 값을 변경하기 위해 -> 포인터로 변수에 접근

    printf("2번째 좌표 입력\n");
    input(&p2);

    printf("p1");
    output(p1); //call by value : 전달하는 변수의 값을 변경할 필요가 없는 경우 -> 복사본 생성

    printf("p2");
    output(p2);

    return 0;
}
#include <stdio.h>
#include <stdlib.h> // malloc, free, rand, srand

#pragma warning(disable : 4996)

typedef struct point
{
    int x;
    int y;
}point;

void input(point* p)
{
    printf("x좌표: ");
    scanf("%d", &p->x);

    printf("y좌표: ");
    scanf("%d", &p->y);
}

void output(point copy)
{
    printf("(%d, %d)\n", copy.x, copy.y);
}

int main(void)
{
    point p1;
    p1.x = 2;
    p1.y = 3;

    point p2;
    p2 = p1; //복사본 생성

    point* p; //주소를 저장하는 포인터 변수(x, y멤버가 할당되는 게 아니다)
    p = &p1; //연결

    p1.x = 100;

    printf("p1(%d %d)\n", p1.x, p1.y); //(100,3)
    printf("p2(%d %d)\n", p2.x, p2.y); //(2,3)
    printf("p(%d %d)\n", p->x, p->y); //(*p).x == p1.x == p->x


    //point p1, p2;

    ///*p1.x = 10;
   // p1.y = 20;

    //p2.x = 100;
    //p2.y = 200;*/

    /*printf("1번째 좌표 입력\n");
    input(&p1); //call by address : 전달하는 변수의 값을 변경하기 위해 -> 포인터로 변수에 접근

    printf("2번째 좌표 입력\n");
    input(&p2);

    printf("p1");
    output(p1); //call by value : 전달하는 변수의 값을 변경할 필요가 없는 경우 -> 복사본 생성

    printf("p2");
    output(p2);
     */

    return 0;
}

Square 구조체

#include <stdio.h>
#include <stdlib.h> // malloc, free, rand, srand

#pragma warning(disable : 4996)

typedef struct square
{
    double width;
    double height;
}square;

void input(square* p)
{
    printf("사각형의 가로 입력 : ");
    scanf("%lf", &p->width);

    printf("사각형의 세로 입력: ");
    scanf("%lf", &p->height);
}

void output(square s)
{
    printf("사격형의 가로는 %f이며, 세로는 %f입니다.\n", s.width, s.height);
}

double getSquareArea(square s)
{
    return s.width * s.height;
}

int main()
{
    square s; //구조체 변수 선언

    input(&s); //가로, 세로값 입력 함수
    output(s); //출력 함수


    //getSqaureArea함수 : 사각형의 넓이를 구해 리턴
    printf("사각형의 넓이는 %f입니다.\n", getSquareArea(s));
    return 0;
}

포인트 구조체 c

#include <stdio.h>
#include <stdlib.h> //malloc, free
#include <math.h> //sqrt

#pragma warning (disable : 4996)

typedef struct point
{
    int x;
    int y;
}point;

void inputPoint(point* ptr, int maxSize)
{
    for(int i = 0; i < maxSize; i++)
    {
        printf("\n%d번째 좌표 입력\n", i + 1);
        printf("x좌표 입력 : ");
        scanf("%d", &ptr[i].x);

        printf("y좌표 입력 : ");
        scanf("%d", &ptr[i].y);
    }
}

void outputPoint(point* ptr, int maxSize)
{
    printf("\n\n* 좌표 리스트 출력 *\n");
    for(int i = 0; i < maxSize; i++)
    {
        printf("p%d(%d, %d)\n", i + 1, ptr[i].x, ptr[i].y);
    }
}

double getDistance(point src, point dest)
{
    int disX = dest.x - src.x;
    int disY = dest.y - src.y;

    double dis;
    dis = sqrt(disX * disX + disY * disY);
    return dis;
}

int main()
{
    point p[3];

    inputPoint(p, 3);
    outputPoint(p, 3);

    double distance;
    distance = getDistance(p[0], p[1]); //두 점의 거리를 구해 리턴
    printf("p[0] 과 p[1] 두 점의 거리는 %.2f입니다.\n", distance);

    distance = getDistance(p[2], p[0]); //두 점의 거리를 구해 리턴
    printf("p[2] 과 p[0] 두 점의 거리는 %.2f입니다.\n", distance);
    return 0;

}

Date 구조체 c

#include <stdio.h>
#include <stdlib.h> //malloc, free
#include <math.h> //sqrt

#pragma warning (disable : 4996)

typedef struct date
{
    int year;
    int month;
    int day;
}date;

void outDate(date da)
{
    printf("%d/%d/%d\n", da.year, da.month, da.day);
}

int isLeapYear(int year)
{
    if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
        return 1; //윤년인 경우? 1리턴
    else
        return 0; //평년인 경우? 0리턴

}

void calc100increase(date* pDate)
{
    int month12[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    pDate->day += 99;

    while(pDate->day - month12[pDate->month]> 0) //월의 최대 일수를 뺼 수 있어?
    {
        if(pDate->month == 2 && isLeapYear(pDate->year))
        {
            month12[2] = 29;
        }
        else
        {
            month12[2] = 28;
        }
        pDate->day = pDate->day - month12[pDate->month];//월의 최대 일수를 빼고
        pDate->month++; //월의 일수를 증가

        if(pDate->month == 13)
        {
            pDate->month = 1; //1월로 변경
            pDate->year++; //년도 증가
        }
    }
}

void calcDaysincrease(date* pDate, int increday)
{
    int month12[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    pDate->day += (increday - 1);

    while(pDate->day - month12[pDate->month]> 0) //월의 최대 일수를 뺼 수 있어?
    {
        if(pDate->month == 2 && isLeapYear(pDate->year))
        {
            month12[2] = 29;
        }
        else
        {
            month12[2] = 28;
        }
        pDate->day = pDate->day - month12[pDate->month];//월의 최대 일수를 빼고
        pDate->month++; //월의 일수를 증가

        if(pDate->month == 13)
        {
            pDate->month = 1; //1월로 변경
            pDate->year++; //년도 증가
        }
    }
}
int main(void)
{
    date d1 = { 2003, 12, 6 };

    printf("시작 일: ");
    outDate(d1);

    calc100increase(&d1);

    printf("시작 일 + 100: ");
    outDate(d1);

    date d2 = { 2023, 12, 12 };

    printf("시작 일: ");
    outDate(d2);

    calcDaysincrease(&d2, 1000));

    printf("시작 일 + 1000= ");
    outDate(d2);

    return 0;
}
#include <stdio.h>
#include <stdlib.h> // malloc, free
#include <math.h>   // sqrt

#pragma warning(disable : 4996)

typedef struct date
{
    int year;
    int month;
    int day;
} date;

void outDate(date da)
{
    printf("%04d/%02d/%02d\n", da.year, da.month, da.day);
}

int isLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

void calc100sincrease(date* pDate)
{
    pDate->day += 100;
    while (pDate->day > 365 + isLeapYear(pDate->year))
    {
        pDate->day -= 365 + isLeapYear(pDate->year);
        pDate->year++;
    }
}

void calcDaysincrease(date* pDate, int increDay)
{
    pDate->day += increDay;
    while (pDate->day > 365 + isLeapYear(pDate->year))
    {
        pDate->day -= 365 + isLeapYear(pDate->year);
        pDate->year++;
    }
}

int main(void)
{
    date d1 = {2003, 12, 6};

    printf("시작 일: ");
    outDate(d1);

    calc100sincrease(&d1);
    printf("시작 일 + 100: ");
    outDate(d1);

    date d2 = {2023, 12, 12};

    printf("시작 일: ");
    outDate(d2);

    calcDaysincrease(&d2, 1000);
    printf("시작 일 + 1000: ");
    outDate(d2);

    return 0;
}

포인트 구조체 동적할당 c

#include <stdio.h>
#include <stdlib.h> //malloc, free
#include <math.h> //sqrt

#pragma warning (disable : 4996)

typedef struct point
{
    int x;
    int y;
}point;

void inputPoint(point* ptr, int maxSize)
{
    for(int i = 0; i < maxSize; i++)
    {
        printf("\n%d번째 좌표 입력\n", i + 1);
        printf("x좌표 입력 : ");
        scanf("%d", &ptr[i].x);

        printf("y좌표 입력 : ");
        scanf("%d", &ptr[i].y);
    }
}

void outputPoint(point* ptr, int maxSize)
{
    printf("\n\n* 좌표 리스트 출력 *\n");
    for(int i = 0; i < maxSize; i++)
    {
        printf("p%d(%d, %d)\n", i + 1, ptr[i].x, ptr[i].y);
    }
}

double getDistance(point src, point dest)
{
    int disX = dest.x - src.x;
    int disY = dest.y - src.y;

    double dis;
    dis = sqrt(disX * disX + disY * disY);
    return dis;
}

int main()
{
    int count;
    printf("생성할 좌표의 개수를 입력 하세요: ");
    scanf("%d", &count);

    //point p[count];
    point* p;
    p = (point*)malloc(sizeof(point)* count); //동적 메모리 할당

    inputPoint(p, count);
    outputPoint(p, count);

    double distance;
    distance = getDistance(p[0], p[1]); //두 점의 거리를 구해 리턴
    printf("p[0] 과 p[1] 두 점의 거리는 %.2f입니다.\n", distance);

    distance = getDistance(p[2], p[0]); //두 점의 거리를 구해 리턴
    printf("p[2] 과 p[0] 두 점의 거리는 %.2f입니다.\n", distance);

    free(p); //동적 메모리 해제
    return 0;

}

Student 구조체 동적할당 c

#include <stdio.h>
#include <stdlib.h> //malloc, free
#include <math.h> //sqrt

#pragma warning (disable : 4996)

#define NAME_LEN 20

typedef struct student
{
    char name[NAME_LEN];
    int kor, eng, mat;
    double avg;
}student;

void input(student* pst, int n)
{
    for(int i = 0; i < n; i++)
    {
        system("clear"); //window=> system("cls")
        printf("%d번 학생명 입력: ", i + 1);
        fgets(pst[i].name, NAME_LEN, stdin); //window=> gets_s(pst[i].name, NAME_LEN);

        printf("국어 영어 수학 점수 입력(공백구분 연속으로) : ");
        scanf("%d %d %d", &pst[i].kor, &pst[i].eng, &pst[i].mat);
        while(getchar() != '\n'); //버퍼에 남아 있는 내용가져오기
        pst[i].avg = (pst[i].kor + pst[i].eng + pst[i].mat) / 3.0;
    }
}
void output(student* pst, int n)
{
    system("clear");
    printf("\n\t* 학생 점수 리스트 출력 *\n");

    for(int i = 0; i < n; i++)
    {
        printf("%-20s %8d %8d %8d %8.2f/n", pst[i].name, pst[i].kor, pst[i].eng, pst[i].mat, pst[i].avg);
    }
}


int main()
{
    int stNum;
    printf("학생 수 입력: ");
    scanf("%d", &stNum);
    while(getchar() != '\n'); //버퍼에 남아있는 내용 가져오기

    //student st[stNum]; //error
    student* st;
    st = (student*)malloc(sizeof(student)* stNum); //student 할당하고 싶은 메모리//메모리 동적 할당


    input(st, stNum);//학생 이름과 정수를 입력받아 평균을 구하는 함수 호출
    output(st, stNum);//구조체에 저장된 데이터를 출력하는 함수 호출

    free(st); //메모리 해제

    return 0;
}
profile
진심입니다.

0개의 댓글