본문 바로가기
C 언어

C언어로 Array of struct 만들기

by treeCoder 2023. 7. 4.

Array of struct 이다.

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

#define Max_Col 512
#define Max_Row 300 // Up to 3000000, it's ok for some computers.

typedef struct Item {
    char name[Max_Col];
    int quantity;
} Item;

void exit_if_null(void *ptr, char *msg) {
    if (!ptr) {
        printf("unexpected null pointer: %s\n", msg);
        exit(EXIT_FAILURE);
    }
}

Item* create_array(int size) {
	Item *p = malloc(size * sizeof(Item));
    exit_if_null(p, "Item memory allocation error\n");
	
    return p;
}

void add_info(Item* items, const char* name, int quantity, int *index) {
	if (*index > Max_Row ) {
        printf("Max data of %d exceeded\n", Max_Row);
        exit(EXIT_FAILURE);
    }
	
	strncpy(items[*index].name, name, Max_Col);
    *(items[*index].name + Max_Col ) = 0;
	
    items[*index].quantity = quantity;
    (*index)++;
}

void print_items(const Item* items, int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("Name: %s, Quantity: %d\n", items[i].name, items[i].quantity);
    }
}

int compare(const void* s1, const void* s2) {

    Item *item1 = (Item *)s1;
    Item *item2 = (Item *)s2;

    return strcmp(item1->name, item2->name);

}

void sort_items(Item* items, int size) {
    qsort(items, size, sizeof(Item), compare);
}

void search_item(const Item* items, const char* name, int size) {
    for (int i = 0; i < size; i++) {
        if (strcmp(items[i].name, name) == 0) {
            printf("Item found: %s, Quantity: %d\n", items[i].name, items[i].quantity);
            return;
        }
    }
    printf("Item not found\n");
}

void free_items(Item* items) {
    free(items);
}

int main() {
    int size = 0;

    Item* items = create_array( Max_Row );

    // Add items
    add_info(items, "Apple", 50, &size);
    add_info(items, "Orange", 30, &size);
    add_info(items, "Banana", 45, &size);
    add_info(items, "Cherry", 10, &size);

    // Print items
    printf("------ Items before sort ------\n");
    print_items(items, size);

    // Sort items
    sort_items(items, size);

    // Print items
    printf("------ Items after sort ------\n");
    print_items(items, size);

    // Search an item
    printf("------ Search an Item ------\n");
    search_item(items, "Banana", size);

    // free items
    free_items(items);

    return 0;
}

실행결과는 다음과 같다.

 

'C 언어' 카테고리의 다른 글

C 언어로 만든 Basic Interpreter  (1) 2024.01.21
Tax calculator  (0) 2023.10.07
C언어로 만든 Hash Table  (0) 2023.05.12
get_string 함수  (0) 2022.10.20
C언어 복리계산  (0) 2022.10.09

댓글