-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
구조체 malloc 으로 문장 입력받기
22.07.04 15:27 작성 조회수 194
0
구조체 할당메모리 강의에서 쓰인 내용을 바꾸어서 배열의 크기를 제가 정하고 문장을 입력받는 코드를 시도해보았습니다.
근데 오류가 뜨고 입력이 안되네요.. 뭐가 잘못된걸까요?
파일 첨부합니다!
답변을 작성해보세요.
0
강민철
2022.07.05
의도하신 코드가 아래와 같이 동작하는 코드인가요?
그렇다면 아래와 같이 작성해야 하는 건 아닌지 확인해보세요.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define SLEN 101
struct book
{
char name[SLEN];
char author[SLEN];
};
void print_book(const struct book *books, int n);
int main()
{
int n;
scanf("%d", &n);
//struct book my_books[3];
struct book* my_books = (struct book*)malloc(sizeof(struct book) * n);
for (int i = 0; i < n; i++) {
scanf("%s", (my_books[i].name));
scanf("%s", (my_books[i].author));
}
if (!my_books) {
printf("malloc failed");
exit(1);
}
print_book(my_books, n);
free(my_books);
return 0;
}
//void print_book(const struct book books[], int n)
void print_book(const struct book *books, int n)
{
for (int i = 0; i < n; i++)
printf("Book %d : \"%s\" written by \"%s\"\n",
i + 1, books[i].name, books[i].author);
}
답변 1