Written by coh at home

정적 메모리 예제 본문

languages/c

정적 메모리 예제

och 2022. 3. 24. 14:00
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#include<string.h>
#include <stdlib.h>

#define N 1024
#define MAXNAME 64

typedef struct {
	int age;
	float score;
	char name[MAXNAME];
}student;

//일일이 data입력하려면 귀찮으니 그냥 random variable로 지정.
void set_student(student* dst)
{
	dst->age = rand() % 100;
	dst->score = rand() % 100;
	int nameLEN = rand() % MAXNAME;
	for (int i = 0; i < nameLEN; i++)
	{
		dst->name[i] = 'a' + rand() % 26;
	}
}

int main(void)
{
	int numstudent = 0;
	student students[N] = { 0 };
	printf("size of students array = %d bytes\n", sizeof(student) * N);

	//sizeof(student)와 무관하게 내가 쓸 data 크기를 결정.
	printf("How many student? ");
	scanf("%d", &numstudent);

	for (int i = 0; i < numstudent; i++)
	{
		set_student(&students[i]);
	}

	float avg = 0;
	for (int i = 0; i < numstudent; i++)
	{
		avg += students[i].score;
	}
	avg /= numstudent;
	printf("Average acore =%.2f\n", avg);
	return 0;
}

정적 메모리의 배열은 그냥 내가 쓸 data갯수와 상관없이 적당히 크게 잡혀 있어야 함.

그 부분을 students[N]으로 잡았음. 

그래서 메모리가 낭비된다. 

'languages > c' 카테고리의 다른 글

보물지도 찾기.  (0) 2022.03.31
c언어 data filter 만들기  (0) 2022.03.29
동적메모리 예제  (0) 2022.03.25
동적메모리  (0) 2022.03.24
.c file I/O studentDB.bin  (0) 2022.03.23