1. P501 사용자가 입력하는 크기의 배열을 만들어 보자.
#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand(), malloc(), free(), exit()
#include <time.h> //time()
#include <string.h> //strcmp()
#include <math.h> // sqrt
#include <windows.h>
int main(void)
{
int* p;
int i, items;
printf("항목의 개수는 몇개입니까? ");
scanf("%d", &items);
p = (int*)malloc(sizeof(int)*items);
for (i = 0; i < items; i++) {
printf("항목(정수)를 입력하시오 : ");
scanf("%d", &p[i]);
}
printf("\n입력된 값은 다음과 같습니다: \n");
for (i = 0; i < items; i++)
printf("%d ", p[i]);
printf("\n");
free(p);
return 0;
}
2. 502P 동적 배열을 난수로 채워보자.
#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand(), malloc(), free(), exit()
#include <time.h> //time()
#include <string.h> //strcmp()
#include <math.h> // sqrt
#include <windows.h>
#define SIZE 1000
int main(void)
{
int* p = NULL;
int i, items;
p = (int*)malloc(SIZE*sizeof(int));
if (p = NULL) {
printf("메모리 할당 오류\n");
exit(1);
}
for (i = 0; i < SIZE; i++)
p[i] = rand();
int max = p[0];
for (i = 1; i < SIZE; i++) {
if (p[i] > max)
max = p[i];
}
printf("최대값=%d \n", max);
free(p);
return 0;
}
3. 506P 동적 구조체 배열
#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
#include <stdlib.h> //rand(), srand(), malloc(), free(), exit()
#include <time.h> //time()
#include <string.h> //strcmp()
#include <math.h> // sqrt
#include <windows.h>
#define SIZE 100
struct movie {
char title[SIZE];
double rating;
};
int main(void)
{
struct movie* ptr;
int i, n;
printf("영화의 개수: ");
scanf("%d", &n);
getchar();
ptr = (struct movie*)malloc(n * sizeof(struct movie));
if (ptr == NULL) {
printf("메모리 할당 오류\n");
exit(1);
}
for (i = 0; i < n; i++) {
printf("영화 제목:");
gets_s(ptr[i].title, SIZE);
printf("영화 평점:");
scanf("%lf", &ptr[i].rating);
getchar();
}
printf("\n====================\n");
for (i = 0; i < n; i++) {
printf("영화 제목: %s \n", ptr[i].title);
printf("영화 평점: %lf \n", ptr[i].rating);
}
printf("====================\n");
free(ptr);
return 0;
}
'C언어 콘서트' 카테고리의 다른 글
C언어 콘서트 12장 파일 입출력 LAB 도전문제 (0) | 2023.09.02 |
---|---|
C언어 콘서트 10장 LAB 풀이 (0) | 2023.09.01 |
c언어 콘서트 10장 문자열 LAB (도전문제 포함) (2) | 2023.08.31 |
C언어 콘서트 챕터9 LAB 유용한 배열 함수 작성 (0) | 2023.08.29 |
C언어 콘서트 8장 미니프로젝트 ATM만들기 P333 (0) | 2023.08.28 |