카테고리

asm (27) bootloader_x86_grub (1) C (92) compile (11) config (76) CPP (13) CSS (1) debugging (7) gimp (1) Go (1) html (1) Java (1) JavaScript (1) kernel (19) LibreOffice (3) Linux system progamming (21) MFC (1) opencv (4) OpenGL (1) PHP (1) Python (4) qemu (29) shell (3) socket (7) troubleshooting (2) ubuntu18.04 (2) windows (1)

2018/12/28

구조체 malloc() 사용법.

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

struct product{
float price;
char productName[30];
};

int main(void){
struct product *pProducts;

int i, j;

int numberOfProducts;
printf("Enter the Number of products to store: ");

scanf("%d", &numberOfProducts);
pProducts = (struct product *) malloc(numberOfProducts * sizeof(struct product));

for(i=0; i < numberOfProducts; ++i){
printf("Enter a Product Name: ");
scanf("%s", &(pProducts+i)->productName);

printf("Enter a Product Price: ");
scanf("%e", &(pProducts+i)->price);

}

printf("Products Stored\n");

for(j=0; j < numberOfProducts; ++j){
printf("%s\t%.2f\n", (pProducts+j)->productName, (pProducts+j)->price);
}

free(pProducts);

return 0;
}

/*
 * ./02_malloc_struct_store
Enter the Number of products to store: 3
Enter a Product Name: Egg
Enter a Product Price: .25
Enter a Product Name: Fish
Enter a Product Price: 11
Enter a Product Name: Bread
Enter a Product Price: 3
Products Stored
Egg 0.25
Fish 11.00
Bread 3.00 */

댓글 없음:

댓글 쓰기