본문 바로가기

C_study

[C] 코딩도장 61 : 함수에서 반환값 사용하기

61.10 심사문제: 게임 캐릭터 능력치 함수 만들기

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

float getArmor() 
{
    return 20.5f; // 20.500000를 리턴
}

bool hasSlowSkill()
{
    return false; // bool값을 리턴
}

int main()
{
    float armor;
    bool slow;

    armor = getArmor();
    slow = hasSlowSkill();

    printf("%f\n", armor); // armor
    printf("%s\n", slow == true ? "true" : "false"); // false
 
    return 0;
}

61.11 심사문제: 문자열 포인터 반환하기

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

char* getName()
{
    char* name = malloc(sizeof(char) * 100);
    strcpy(name, "Neptune");
    return name;
}


int main()
{
    char *name; 

    name = getName(); // 메모리를 할당받은 다음 Neptune 문자열이 입력된 값을 받아야 함
 
    printf("%s\n", name);

    free(name);

    return 0;
}

61.12 심사문제: 메모리 할당 함수 만들기

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

void *allocMemory()
{
    return malloc(100); // 포인터를 반환해도 되고, 바로 반환해도 된다
}

int main()
{
    char *name;
    float *stats;

    name = allocMemory(); // 동적 메모리 할당
    strcpy(name, "Mercury"); // name 메모리에 Mercury 복사
    printf("%s\n", name);
    free(name); // 동적 메모리 할당 해제

    stats = allocMemory();
    stats[0] = 87.969f;
    stats[1] = 115.8776f;
    printf("%f %f\n", stats[0], stats[1]);
    free(stats);

    return 0;
}

61.13 심사문제: 2차원 정보 만들기

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

struct Point2D {
    int x;
    int y;
};

struct Point2D *allocPoint2D() // 함수 안에서 구조체 변수에 값을 할당해야함
{
    struct Point2D *pos = malloc(sizeof(struct Point2D)); // 구조체 포인터 선언 후 메모리 할당
    pos->x = 90; // 화살표 연산자로 멤버 변수에 접근, 값 할당 
    pos->y = 75;
    return pos; // 구조체 포인터 반환
}

int main()
{
    struct Point2D *pos1;

    pos1 = allocPoint2D();

    printf("%d %d\n", pos1->x, pos1->y);

    free(pos1);

    return 0;
}