C - 구조체 동적할당

원종서·2023년 2월 16일
0

C

목록 보기
2/3

구조체 동적할당

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

struct Something {
int a, b;
}

int main(){
	struct Something *arr;
    int size, i;
    
    scanf("%d", &size);
    
    arr = (struct Something *)malloc(sizeof(struct Something) * size);
    
    for(int i = 0 ; i< size ; i++){
    	scanf("%d", &arr[i].a);
        scanf("%d", &arr[i].b);
    }
    
    // use arr...
    
    free(arr);
}

노드


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

struct Node {
	int data;
    struct Node* next;
}

// 노드 생성
struct Node* createNode(int data) {
	struct Node* node = (struct Node *)malloc(sizeof(struct Node));
    
    node->data = data;
    node->next = null;
    
    return node;
}

struct Node * insertNode(struct Node * current , int data) {
	
    struct Node * after = current->next;
    
    struct Node *  newNode = (struct Node *)malloc(sizeof(struct Node));
    
    newNode->data = data;
    newNode->next = after;
    
    current->next= newNode;
    
    return newNode;
}

void destoryNode(struct Node * destory , struct Node * header){
	struct Node * next= header;
    
    while(next == destory){
         free(destory);
         return;
    }
    
    while(next){
    	if(next->next == destory){	
        	next->next = destory->next;
            free(destory);
            return;
        }
        next = next->next;
    }
}

메모리 관련 함수

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

int main(){
	char str[50] = "I love Cheing C hahaha";
    char str2[50];
    char str3[50];
    
    // strlen(string) -> not count NULL char
    memcpy(str2, str, strlen(str)+1);
    memcpy(str3, "hello", 6);
    
    // str+17에서 65개의 문자를  str+23에 옮기다.
    // 옮기는 메모리의 공간이 겹쳐도 가능.
    memmove(str+23, str+17,6);
    
    int arr[10] ={1,2,3,4,5};
    int arr2[10] ={1,2,3,4,5};
    
    // arr과 arr2를 비교해서 처음 5개의 바이트(!) 가 같다면 0
    if(memcmp(arr,arr2, 5) == 0){
    
    }
    
}

0개의 댓글