U E D R , A S I H C RSS

새싹교실/2018/C알/4월11일


1. 진행

  • 화요일 휴강, 급히 보강
  • function, 선언 후 정의
  • function pointer
  • void qsort(void*, size_t, size_t, int (*)(int,int));
  • structure type

  • 실습 : 정수 동적 배열 자료구조 int_arr을 만들자

typedef struct
{
        size_t len;
        int* ptr;
} int_arr;

int_arr* init(size_t cap);

int ia_get(int_arr* ia_p, size_t idx, int val);
int ia_set(int_arr* ia_p, size_t idx);
int ia_insert(int_arr* ia_p, size_t idx, int val);
int ia_delete(int_arr* ia_p, size_t idx);
int ia_push(int_arr* ia_p, int val);
int ia_pop(int_arr* ia_p);
int ia_sort(int_arr* ia_p, int order);//ascending(if true) or desending(if false)

2. 실습


  • 승진 - 작동 안되요

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

typedef struct
{
	size_t len;
	int* ptr;
} int_arr;

int_arr* init(size_t cap);

int ia_set(int_arr* ia_p, size_t idx, int val);
int ia_get(int_arr* ia_p, size_t idx);
int ia_insert(int_arr* ia_p, size_t idx, int val);
int ia_delete(int_arr* ia_p, size_t idx);
int ia_push(int_arr* ia_p, int val);
int ia_pop(int_arr* ia_p);
int ia_sort(int_arr* ia_p, int order);

int main(){
	int_arr* arr1 = init(5);

	ia_set(arr1, 2, 1);
	printf("%d\n", ia_get(arr1, 2));

	ia_insert(arr1, 3, 10);
	ia_delete(arr1, 3);

	ia_push(arr1, 5);
	printf("%d\n", ia_pop(arr1));

	system("pause");
	return 0;
}

int_arr* init(size_t cap){
	int_arr arr;
	int_arr* tmp = &arr;

	arr.len = cap;
	arr.ptr = (int*)malloc(sizeof(int)*arr.len);
	for (int i = 0; i < arr.len; i++)
		arr.ptr[i] = 0;

	return tmp;
}
int ia_set(int_arr* ia_p, size_t idx, int val){
	ia_p->ptr[idx] = val;
	return ia_p->ptr[idx];
}
int ia_get(int_arr* ia_p, size_t idx){
	return ia_p->ptr[idx];
}
int ia_insert(int_arr* ia_p, size_t idx, int val){
	for (int i = ia_p->len; i >= idx; i--)
		ia_p->ptr[i] = ia_p->ptr[i - 1];
	ia_p->ptr[idx] = val;
	ia_p->len++;

	return ia_p->ptr[idx];
}
int ia_delete(int_arr* ia_p, size_t idx){
	int tmp = ia_p->ptr[idx - 1];

	for (int i = idx - 1; i < ia_p->len - 1; i++)
		ia_p->ptr[i] = ia_p->ptr[i + 1];
	ia_p->len--;

	return tmp;
}
int ia_push(int_arr* ia_p, int val){
	ia_p->ptr[ia_p->len++] = val;

	return ia_p->ptr[ia_p->len - 1];
}
int ia_pop(int_arr* ia_p){
	ia_p->len--;
	return ia_p->ptr[ia_p->len];
}
int ia_sort(int_arr* ia_p, int order){
	int tmp;
	for (int i = ia_p->len; i > 1; i--){
		for (int j = 1; j < i; j++){
			if (ia_p->ptr[j - 1]>ia_p->ptr[j] && order){
				tmp = ia_p->ptr[j - 1];
				ia_p->ptr[j - 1] = ia_p->ptr[j];
				ia_p->ptr[j] = tmp;
			}
		}
	}

	return order;
}

3. 기타 / 후기 / 방명록


새싹교실/2018/C알
새싹교실/2018
  • 동적할당 했으니 풀어주는 함수도 있어야 하지 않을까요? - 승진
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:30:10
Processing time 0.0144 sec