Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

문타쿠, 공부하다.

[C언어 코딩 도장] Unit 49. 연습문제 및 심사문제 본문

C언어/C언어 코딩 도장

[C언어 코딩 도장] Unit 49. 연습문제 및 심사문제

개발새발 문타쿠 2023. 10. 29. 02:44

49.5 연습문제: 학생 구조체 포인터에 메모리 할당하기

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student
{
    char name[20];
    int grade;
    int class;
    float average;
};

int main(void)
{
    struct Student* s1 = malloc(sizeof(struct Student));

    strcpy(s1->name, "고길동");
    s1->grade = 1;
    s1->class = 3;
    s1->average = 65.389999f;

    printf("이름: %s\n", s1->name);
    printf("학년: %d\n", s1->grade);
    printf("반: %d\n", s1->class);
    printf("평균점수: %f\n", s1->average);

    free(s1);   

    return 0;
}

49.6 연습문제: 3차원 좌표 구조체 포인터에 메모리 할당하기

#include <stdio.h>
#include <stdlib.h>

typedef struct _Point3D
{
    float x;
    float y;
    float z;

} Point3D;

int main(void)
{
    Point3D* p1 = malloc(sizeof(Point3D));

    p1->x = 10.0f;
    p1->y = 20.0f;
    p1->z = 30.0f;

    printf("%f %f %f\n", p1->x, p1->y, p1->z);

    free(p1);   

    return 0;
}

49.7 연습문제: 구조체 포인터에 구조체 주소 할당하기

#include <stdio.h>
#include <stdbool.h>

struct Item
{
    char name[100];
    int price;
    bool limited;

};

int main(void)
{
    struct Item item1 = { "베를린 필하모닉 베토벤 교향곡 전집", 100000, false };
    struct Item* ptr;

    ptr = &item1;

    ptr->limited = true;

    if (ptr->limited == true)
        printf("한정판\n");
    else
        printf("일반판\n");

    return 0;
}

49.8 심사문제: 사람과 자동차 구조체 포인터에 메모리 할당하기

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Person
{
    char name[20];
    int age;
    char address[100];

};

typedef struct
{
    char name[20];
    int number;
    int displacement;

} Car;

int main(void)
{
    struct Person* p1 = malloc(sizeof(struct Person));

    strcpy(p1->name, "고길동");
    p1->age = 40;
    strcpy(p1->address, "서울시 서초구 반포동");

    Car* c1 = malloc(sizeof(Car));

    strcpy(c1->name, "스텔라");
    c1->number = 3421;
    c1->displacement = 2000;

    printf("이름: %s\n", p1->name);
    printf("나이: %d\n", p1->age);
    printf("주소: %s\n\n", p1->address);
    printf("자동차 이름: %s\n", c1->name);
    printf("자동차 번호: %d\n", c1->number);
    printf("배기량: %dcc\n", c1->displacement);

    free(p1);
    free(c1);

    return 0;
}


49.9 심사문제: 구조체 포인터에 구조체 변수의 주소 할당하기

#include <stdio.h>

struct Point3D
{
    float x;
    float y;
    float z;
};

int main(void)
{
    struct Point3D p1 = { 10.0f, 20.0f, 30.0f };
    struct Point3D* ptr;
    
    ptr = &p1;

    printf("%f %f %f\n", ptr->x, ptr->y, ptr->z);

    return 0;
}