본문 바로가기
c & c++/메모리

동적할당 calloc 함수 이용

by 일상코더 2022. 7. 27.

동적할당 calloc 함수로 구현

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

int main(void)
{
	int i , n;
	printf("처리할 데이터 수는 : ");
	scanf("%d", &n);
	
	int* iPtr = (int*)calloc(n, sizeof(int));  //malloc함수 반환값은 void 
											//사용자가 원하는 반환타입으로 설정 
											
	if(iPtr == '\0')  						//iPtr이 null 이면 할당 실패!
	{
		puts("동적 할당 실패!!"); 
	 } 
	printf("\n %d개의 정수 입력 \n\n", n);
	
	for(i = 0 ; i < n; i++)
	{
		printf("[%d]번 째 정수 : ", i);
		scanf("%d", iPtr+i); 				//포인터 자체가 주소값을 
	}										//담고있는 변수임으로 하나씩 더해줌 
	printf("\n %d의 정수 출력 \n", n);
	for(i = 0 ; i < n; i++)
	{
		printf("[%d] ==> %d \n", i, *(iPtr+i));
	}
	
	printf("%d ", &iPtr);  	//지역변수에있음
	printf("%d ", iPtr);   	//힙영역 iPtr의 시작주소
	printf("%d ", iPtr[1]);	//힙영역에 존재하는 iPtr 두번째 참조값; = *(iPtr+1); 
	
	
	free(iPtr); 			//할당에 성공했음으로 해제 
	
	return 0;
}

'c & c++ > 메모리' 카테고리의 다른 글

동적할당 malloc함수 이용  (0) 2022.07.27
동적할당(malloc)  (0) 2022.07.26

댓글