[자료구조] 메모리 동적 할당 c

K근형·2023년 12월 7일
0

자료구조

목록 보기
2/12

메모리 동적 할당

#include <stdio.h>
#include <stdlib.h> //malloc, free
#pragma warning (disable : 4996)

int main(void)
{
    int stNum;
    int* score;
    printf("학생 수 입력 : ");
    scanf("%d", &stNum);
  
    //int score[stNum]; //정적 할당 : 컴파일 타임에 크기가 결정돼야 한다.
    //동적 할당 : 런 타임(실행 중)에 크기가 결정돼야 한다.
 

    //포인터 = (포인터타입)malloc(할당할 byte크기);
    score = (int*)malloc(sizeof(int) * stNum);

    //free(포인터);//포인터가 가리키는 메모리를 제거
    free(score); //score가 가리키는 메모리를 제거

    //double d[stNum]; => error
    double* d;
    d = (double*)malloc(sizeof(double) * stNum);
    free(d);

    //char c[stNum];
    char* c;
    c = (char*)malloc(sizeof(char) * stNum);
    free(c);


    return 0;
}

학생 성적 평균 c

기본적인 방법

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

#pragma warning (disable : 4996)

int main(void)
{
    int stNum;
    printf("학생 수 입력:");
    scanf("%d", &stNum);

    //정적 할당 : 배열은 컴파일 시 크기를 결정해야 한다.
    // in score[stNum]; //error : 배열의 크기로 변수 불가능

    //동적 할당: 실행 중에 메모리를 할당
    //포인터 = (형 변환)malloc(byte크기);
    int* score;
    score = (int*)malloc(sizeof(int) * stNum);
    printf("프로그램 실행 중 메모리 할당(동적 할당)\n");

    int total = 0;
    for(int i = 0; i < stNum; i++)
    {
        printf("%d번 학생 점수 입력: ", i + 1);
        scanf("%d", &score[i]);
        total += score[i];
    }

    printf("\n총점 : %d, 평균 : %.2f\n", total, (double)total / stNum);

    free(score); //score가 가리키는 메모리를 제거
    return 0;

}

추가 디테일 코드

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

#pragma warning(disable : 4996)

int main(void)
{
    int stNum;
    printf("학생 수 입력: ");
    scanf("%d", &stNum);

    // 동적 할당: 실행 중에 메모리를 할당
    // 포인터 = (형 변환)malloc(바이트 크기);
    int* score;
    score = (int*)malloc(sizeof(int) * stNum);

    if (score == NULL)
    {
        printf("메모리 할당에 실패했습니다.\n");
        return 1; // 오류 코드 반환
    }

    printf("프로그램 실행 중 메모리 할당(동적 할당)\n");

    int total = 0;
    for (int i = 0; i < stNum; i++)
    {
        printf("%d번 학생 점수 입력: ", i + 1);
        scanf("%d", &score[i]);
        total += score[i];
    }

    printf("\n총점: %d, 평균: %.2f\n", total, (double)total / stNum);

    free(score); // score가 가리키는 메모리를 제거
    return 0;
}

학생 평균 신장 c

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

#pragma warning (disable : 4996)

int main(void)
{
    int stNum;
    printf("학생 수 입력:");
    scanf("%d", &stNum);

    //정적 할당 : 배열은 컴파일 시 크기를 결정해야 한다.
    //double height [stNum]; //error : 배열의 크기로 변수 불가능

    //동적 할당: 실행 중에 메모리를 할당
    //포인터 = (형 변환)malloc(byte크기);
    double* height;
    height = (double*)malloc(sizeof(double) * stNum);

    /*if (height == NULL)
    {
    	print("메모리 할당에 실패했습니다.\n");
        return 1; //오류 코드 반환
    }*/

    printf("프로그램 실행 중 메모리 할당(동적 할당)\n");

    double total = 0;
    for(int i = 0; i < stNum; i++)
    {
		//입력 시 %f(float), %lf(double)
        printf("%d번 학생 신장 입력: ", i + 1);
        scanf("%lf", &height[i]);
        total += height[i];
    }

    //출력 시 %f(float, double), %lf(double)
    printf("\n총점 : %.2f, 평균 : %.2f\n", total, total / stNum);

    free(height); //height가 가리키는 메모리를 제거

    return 0;

}

대문자 랜덤 저장 c

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

#pragma warning (disable : 4996)

int main(void)
{
    int uCnt;

    printf("대문자 개수 입력 : ");
    scanf("%d", &uCnt);

    //char upper[uCnt];
    char* upper;
    upper = (char*)malloc(/*sizeof(char)* */uCnt); //동적 할당

    //대문자를 랜덤하게 저장
    srand((unsigned int)time(NULL));

    for(int i = 0; i < uCnt; i++)
    {
        upper[i] = rand() % 26 +65; //'A'(65) ~ 'Z'(90)
    }
    //베열에 저장된 값을 출력
    printf("* 랜덤하게 저장된 대문자 출력 *\n");
    for(int i = 0; i < uCnt; i++)
    {
        printf("%4c", upper[i]);

        if(i % 10 == 9)//if(i == 9 || i == 19 || i ==29)
        {
            puts("");
        }
    }
    puts(""); //줄바꿈

    free(upper); //동적 메모리 해제

    return 0;

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

#pragma warning(disable : 4996)

void upperRandomize(char *up, int count)
{
    srand((unsigned int)time(NULL));

    for (int i = 0; i < count; i++)
    {
        up[i] = rand() % 26 + 65; //'A'(65) ~ 'Z'(90)
    }
}

void displayUpper(char *up, int count)
{
    printf("* 랜덤하게 저장된 대문자 출력 *\n");
    for (int i = 0; i < count; i++)
    {
        printf("%4c", up[i]);

        if (i % 10 == 9) // if(i == 9 || i == 19 || i ==29)
        {
            puts("");
        }
    }
}

int getSearchchChar(char *up, int count, char ch)
{
    int matchch = 0;
    for (int i = 0; i < count; i++)
    {
        if(up[i] == ch) // 일치하는 문자가 있다면?
        {
            ++matchch;
        }

    }
    return matchch;
}

int main(void)
{
    int uCnt;

    printf("대문자 개수 입력: ");
    scanf("%d", &uCnt);
    while (getchar() != '\n')
        ; // 버퍼에 남아 있는 문자를 가져오기, 14번 영상 참조

    // char upper[uCnt];
    char *upper;
    upper = (char *)malloc(uCnt); // 동적 할당

    upperRandomize(upper, uCnt); // 대문자를 랜덤하게 저장

    displayUpper(upper, uCnt); // 배열에 저장된 값을 출력

    char searchCh;
    printf("\n\n검색 문자 입력: ");
    scanf(" %c", &searchCh); // Added a space before %c to consume any whitespace characters

    // 배열에서 검색 문자의 개수를 구해 리턴하는 함수
    int count = getSearchchChar(upper, uCnt, searchCh);
    printf("\n검색 문자의 개수는 %d개 입니다.\n", count);

    puts(""); // 줄바꿈

    free(upper); // 동적 메모리 해제

    return 0;
}

회문판별c

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

#pragma warning(disable : 4996)

int isPalindrome(char* str)
{

    //char copy[255];

    char* copy;
    copy = (char*)malloc(strlen(str) + 1);

    strcpy(copy, str);   // 원래 문자열을 복사
    strrev(copy);        // 복사본 배열을 역순 저장

    // 주석 처리된 코드는 주소 비교였으나, 문자열 비교에는 strcmp 사용
    // if(copy == str)
    if (strcmp(copy, str) == 0) // strcmp: 두 문자열이 같으면 0을 리턴
    {
        free(copy);
        return 1;
    }
    else
    {
        free(copy);
        return 0;
    }
}

int main(void)
{
    char str[255];
    printf("문자열 입력: ");
    fgets(str, 255, stdin); // gets_s(str, 255);

    // isPalindrome: 회문이면 1, 평문이면 0을 리턴
    if (isPalindrome(str))
    {
        printf("%s는 회문입니다.\n", str);
    }
    else
    {
        printf("%s는 회문이 아닙니다.\n", str);
    }
    return 0;
}

개선된 코드

#include <stdio.h>
#include <stdlib.h> // malloc, free
#include <string.h> // strcpy, strcmp

#pragma warning(disable : 4996)

int isPalindrome(const char* str)
{
    int length = strlen(str);

    // 동적 할당: 원래 문자열의 길이 + 1 크기로 메모리 할당
    char* copy = (char*)malloc(length + 1);

    if (copy == NULL)
    {
        printf("메모리 할당에 실패했습니다.\n");
        return 0; // 실패 시 회문이 아니라고 처리
    }

    strcpy(copy, str);         // 원래 문자열을 복사
    strrev(copy);              // 복사본 배열을 역순 저장

    // strcmp: 두 문자열이 같으면 0을 리턴
    int result = (strcmp(copy, str) == 0);

    free(copy); // 동적으로 할당한 메모리를 해제

    return result;
}

int main(void)
{
    char str[255];
    printf("문자열 입력: ");
    fgets(str, sizeof(str), stdin); // sizeof 사용하여 버퍼 오버플로우 방지

    // 개행 문자 제거
    size_t length = strlen(str);
    if (length > 0 && str[length - 1] == '\n')
    {
        str[length - 1] = '\0';
    }

    // isPalindrome: 회문이면 1, 평문이면 0을 리턴
    if (isPalindrome(str))
    {
        printf("%s는 회문입니다.\n", str);
    }
    else
    {
        printf("%s는 회문이 아닙니다.\n", str);
    }
    return 0;
}

Mac에서 strrev 불가..

=>

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

#pragma warning(disable : 4996)

void reverseString(char* str)
{
    int length = strlen(str);
    int i, j;
    char temp;

    for (i = 0, j = length - 1; i < j; i++, j--)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

int isPalindrome(char* str)
{
    char copy[255];

    strcpy(copy, str);   // 원래 문자열을 복사
    reverseString(copy); // 복사본 배열을 역순 저장

    // 주석 처리된 코드는 주소 비교였으나, 문자열 비교에는 strcmp 사용
    // if(copy == str)
    if (strcmp(copy, str) == 0) // strcmp: 두 문자열이 같으면 0을 리턴
        return 1;
    else
        return 0;
}

int main(void)
{
    char str[255];
    printf("문자열 입력: ");
    fgets(str, 255, stdin); // gets_s(str, 255);

    // isPalindrome: 회문이면 1, 평문이면 0을 리턴
    if (isPalindrome(str))
    {
        printf("%s는 회문입니다.\n", str);
    }
    else
    {
        printf("%s는 회문이 아닙니다.\n", str);
    }
    return 0;
}
profile
진심입니다.

0개의 댓글