본문 바로가기

프로그래밍/C 프로그래밍

[C언어] 메모리 동적 할당

  • calloc() 함수
    • malloc() 함수와 동일하게 힙 영역에 기억공간 할당
    • 할당된 기억공간 0으로 초기화수
void * calloc(n, sizeof(int))
.// 주어진 size의 크기를 가지는 기억공간 n개를 할당 받는다.
#include <stdio.h>
#include <stdlib.h>

int main(){
	int i;
	int *a;
	
	a = (int *)calloc(5, sizeof(int));
	
	for(i=0; i<5; i++)
		printf("%d\n", a[i]);
	
	free(a);
}
/*
0
0
0
0
0
*/

 

  • realloc() 함수
    • 이미 할당 받은 기억 공간의 크기를 변경해야 할 필요가 있을 경우 사용
void * realloc(void *p, int size)
// 포인터 p가 가리키고 있는 기억공간의 크기를 지정된 size 크기로 변경

 

int *a;

a=(int *) calloc(5,sizeof(int));
// int형 크기의 기억공간 5개 할당
a=(int *) realloc(a,10*sizeof(int));
// int형 크기의 기억공간 10개 재할당.
#include <stdio.h>
#include <stdlib.h> // malloc(), free() 함수

int main(){
	char *str[5];
	int i;
	
	for(i=0; i<5; i++){
		//5개의 변수에 대해 128바이트공간 확보하기. 
		if((str[i] = (char*)malloc(128)) == NULL){
			//malloc(): 동적 메모리 할당 함수
			printf("메모리 할당 실패 \n");
			exit(0); 
		}
		
		printf("메모리 할당 성공, 문자열[%d]를 입력하세요 \n", i+1);
		gets(str[i]);
		
	}
	for(i=0; i<5; i++)
		free(str[i]); //동적 메모리 해제 
}

 

[실습] 문자열 입력받아 알파벳순으로 버블정렬

#include <stdio.h>
#include <stdlib.h> //동적 메모리할당 위한 함수 포함 

int main(){
	char temp, *str;
	int i, j , k;
	
	str = (char*)malloc(128); //문자 입력받기 위한 메모리 동적 할당, malloc 함수는 void*를 반환하므로 char*로 형변환. 
	for (i=0; (*str++=getchar())!='\n';i++) //키보드로부터 문자 입력받아 *str에 대입하고 다음 문자 위치로 이동
	//i는 입력된 문자 갯수 센다.
	 
	*str='\0'; //문자열 끝에 null문자 추가
	str-=i+1;  //포인터 str을 문자열 시작 위치로 이동. i+1을 빼주는 이유는 str이 한 번 더 증가했기 때문.
	for(j=1;j<i;j++)
		for(k=1; k<i; k++)
			if(*(str+k)<*(str+k-1)){
				temp =* (str+k); //버블정렬
				*(str+k) = *(str+k-1);
				*(str+k-1)=temp; 
			} 
			
	printf("\n%s", str);

} 

/*
computer science

 ccceeeimnoprstu
 */

 

# 힙데이터에 저장

 

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

int main(){
	int *intptr;
	float *floatptr;
	char *name;
	
	intptr=(int *)malloc(sizeof(int));
	floatptr = (float *)malloc(sizeof(float)); // 힙에서 메모리 얻어옴 
	name=(char *)malloc(sizeof(char)); //힙에서 20문자만큼 메모리 얻어옴.
	
	*intptr = 25;
	*floatptr = 3.141592;
	printf("이름은?");
	gets(name);
	
	printf("저장된 값: \n");
	printf("\t *intptr =%d \n", *intptr);
	printf("\t *floatptr=%f \n", *floatptr);
	printf("\t  name=%s\n", name);
	
	free(floatptr);
	free(name);
	
	
}

 

[실습] 문자열 입력받아 단어를 역으로 출력하는 프로그램

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

int main(){
	int maxlen, len, i;
	char *str;
	printf("Input length of max string: ");
	scanf("%d", &maxlen);
	getchar(); //scanf 이후에 남아있는 개행문자('\n') 제거. 
	
	str= (char *)malloc(sizeof(char)*(maxlen+1));
	
	printf("string input: ");
	fgets(str,maxlen+1, stdin);
	
	for(i=len; i>=0; i--){
		if(str[i] ==' '){
			printf("%s ", &str[i+1]);
			
			str[i]='\0';
		}
	}
	printf("%s", &str[0]);
	free(str);
}

 

[실습] 문자열 입력받아 문자수, 단어수 산정하는 프로그램

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

int main(){
	int maxlen, len, i;
	char *str;
	printf("Input length of max string: ");
	scanf("%d", &maxlen);
	getchar(); //scanf 이후에 남아있는 개행문자('\n') 제거. 
	
	str= (char *)malloc(sizeof(char)*(maxlen+1));
	
	printf("string input: ");
	fgets(str,maxlen+1, stdin);
	
	for(i=len; i>=0; i--){
		if(str[i] ==' '){
			printf("%s ", &str[i+1]);
			
			str[i]='\0';
		}
	}
	printf("%s", &str[0]);
	free(str);
}

 

  • memcpy(): 기억공간의 자료를 다른 기억 공간 영역으로 복사하기 위한 함수
void *memcpy(void *dest, const void *src, size_t n)
//src에서 n byte만큼 dest에 복
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
	char src[] = "1234567890";
	char dest[] = "abcdefghijklmnopqrstuvw";
	
	char *stat;
	
	printf("memcpy() 실행 전 dest의 데이터: %s \n", dest);
	
	stat = (char *)memcpy(dest, src, strlen(src));
	//src의 첫 부분에서부터 문자열의 길이(strlen)만큼의 자료를 dest에 복사. 
	
	if(stat)
		printf("memcpy() 실행 후 dest의 데이터: %s\n", dest);
	else
		printf("복사실패 \n");
}

/*
memcpy() 실행 전 dest의 데이터: abcdefghijklmnopqrstuvw
memcpy() 실행 후 dest의 데이터: 1234567890klmnopqrstuvw
*/
  • memset(): 기억 공간의 자료를 지정한 문자로 채우는 함수
    • 할당된 기억 공간의 초기화나 내용 삭제를 위해 주료 사용
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
	char s[] = "1234567890";
	printf("memset() 실행 전 데이터: %s \n", s);
	memset(s, '*', 5);
	printf("memset() 실행 후 데이터: %s \n", s);
}
반응형

'프로그래밍 > C 프로그래밍' 카테고리의 다른 글

[C언어] typedef  (0) 2024.06.06
[C언어] 파일 입출력  (0) 2024.06.06
[C언어] 파일처리함수  (0) 2024.06.06
[C언어] 구조체와 공용체  (0) 2024.06.06
[C언어] 포인터 및 참조  (0) 2024.06.05