소프트웨어 개발/Algorithm

알아둬야 할 stdlib.h 주요 함수들

Leo's notes 2019. 2. 19. 21:30

void *malloc(size_t size);

memory allocation
size만큼 메모리를 할당하고 메모리 영역을 가리키는 void*형 포인터 반환

int *ptr = (int *) malloc(5*sizeof(int)); 

void *calloc(size_t nitems, size_t size); 

contiguous allocation
malloc과 동일하지만 size*nitems만큼 할당하며, 할당된 공간의 값을 모두 0으로 변환한다.

int *ptr = (int *) calloc(5, sizeof(int)); 

void *realloc(void *ptr, size_t size);

malloc과 동일하지만 ptr이 가리키는 곳의 할당된 메모리를 size 크기로 재할당, 기존 할당된 메모리 내 값들은 유지

int *ptr = (int *) realloc(10*sizeof(int)); 

void free(void *ptr);

ptr이 가리키는 곳에 할당된 메모리를 해제

free(ptr); 


void qsort(void *arr, size_t n, size_t size, int (*comp)(const void *, const void *));

Example

int compare(const void *a, const void *b) {
return *((int *)a) - *((int *)b);
}

int main() {
int arr[10] = {3, 6, 9, 2, 4, 8, 1, 5, 7, 0};
qsort(arr, 10, sizeof(int), compare);
return 0;
}

double atof(const char *str);

문자열을 double 형으로 변환

int atoi(const char *str);

문자열을 int 형으로 변환

int atol(const char *str);

문자열을 long 형으로 변환

int abs(int x);

x의 절대값을 반환


int rand(void);

srand로 지정된 seed값에 따라 난수를 생성

void srand(unsigned int seed);

rand로 난수를 생성하기 위한 seed값을 지정한다.
seed값이 같다면 생성되는 난순열도 같다.

srand(time(NULL));
int random = rand() % 10;