구조체 동적 할당 질문합니다!

p952973의 이미지

텍스트 파일에서 읽어와 라인에 따라 학생과 이름 동적 할당 후 fscanf를 통해 변수에 저장하고 싶습니다.

하지만 동적할당에서 에러가 나네요ㅠㅠ

stdu[i]->name = (char*)malloc(sizeof(char)*30);

이부분에서 에러가 발생하는데 이유를 모르겠습니다. 잘하는분들 도와주세요!

#include
#include
#include

struct student{
char *name;
int math, kor, eng, sum;
float avg;
}

void main(void)
{
typedef struct student stu;

FILE *pFile;
pFile = fopen("grade.txt", "r");
int cnt=0; // 라인수 저장변수...
int i=0;

if(pFile==NULL)
{
printf("이 파일은 존재하지 않습니다\n");
}

while(!feof(pFile))
{
stu *stud[i];
stud[i] = (stu*)malloc(sizeof(stu));
stud[i]->name = (char*)malloc(sizeof(char)*30));
fscanf(pFile,"%s %d %d %d", stud[i]->name,&stud[i]->math,&stud[i]->kor,&stud[i]->eng);
i++
}

}

mirheekl의 이미지

배열인 경우 상수 사이즈로의 선언만 가능할텐데요. 그 부분이 일단 잘못된 걸로 보입니다. 그리고 배열로 어찌어찌 처리를 한다 해도 루프 밖에서 선언해야 합니다.

학생 수가 몇 명인지 미리 알 수 없어서 문제가 된다면, 링크드 리스트 등의 동적 컨테이너를 사용하는 것이 맞는 방법입니다.

또는, 메모리 할당은 않고 일단 파일을 한번 쭉 다 읽어보는 방법으로 레코드가 몇 개인지 (= 파일 안에 텍스트가 몇 줄인지) 알아내고 메모리 할당을 한 다음에 다시 처음부터 읽어 저장하는 방법도 가능하긴 합니다. 이러면 컨테이너를 쓰지 않아도 가능하지요.

그리고 또 보완할 부분이 있다면, 파일 포맷 오류나 잘못된 레코드에 대한 예외처리가 없는 것 같네요. 입력 파일에 오류가 없다는 보장이 없다면, 이 부분도 따로 처리를 해주셔야 합니다.

--

klara의 이미지

가변 길이 배열(VLA)라고 C99부터 가능합니다.
일단 프로그램이 죽는 이유는 크기 i의 배열에서 가장 큰 인덱스는 i-1이어야하기때문인데 아마 의도하는 바는 mirheekl님대로일듯 하네요.

p952973의 이미지

지적해주신대로 라인수 파악 후 배열 선언했습니다.

stud[i]->name = (char*)malloc(sizeof(char)*30));

이 라인만 컴파일 에러가 발생하네요 구조체의 포인터 변수에 ->로 접근하는게 맞지 않나요?
#include
#include
#include

struct student{
char *name;
int math, kor, eng, sum;
float avg;
};

int main(void)
{
typedef struct student stu;

FILE *pFile;
pFile = fopen("grade.txt", "r");
int cnt=0; // 라인수 저장변수...
int i;
char mystring[100];

if(pFile==NULL)
{
printf("이 파일은 존재하지 않습니다\n");
}

while(!feof(pFile))
{
fgets(mystring,100,pFile);
cnt++;
}
printf("%d\n", cnt);
stu *stud[cnt];


for(i=0;i {
stud[i] = (stu*)malloc(sizeof(stu));
stud[i]->name = (char*)malloc(sizeof(char)*30));
fscanf(pFile,"%s %d %d %d", stud[i]->name,&stud[i]->math,&stud[i]->kor,&stud[i]->eng);
i++;
}
return 0;

}

mirheekl의 이미지

좌측 괄호는 두개인데 우측 괄호는 세 개네요.

--

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.