2014-11-01 3 views
3

간단한 학생 데이터베이스 프로그램 연습을하고 있고 구조체 배열을 초기화하는 방법을 잘 모르겠습니다. 컴파일 시간에 알려진 값으로 배열 stdt[]의 처음 세 요소를 초기화하려고 시도하고 다음 3 명의 학생 정보가 사용자 입력에서 채워집니다. 컴파일하면 오류가 발생합니다 :C에서 구조체 배열 초기화하기

lab7.c: In function ‘main’: 

lab7.c:16:9: error: expected expression before ‘{’ token 
stdt[0]={"John","Bishop","s1234","Inf",'m',18}; 
     ^

lab7.c:17:9: error: expected expression before ‘{’ token 
stdt[1]={"Lady","Cook","s2345","Eng",'f',21}; 
     ^

lab7.c:18:9: error: expected expression before ‘{’ token 
stdt[2]={"James","Jackson","s33456","Eng",'m',17}; 
     ^

어떻게하면됩니까?

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

typedef struct { 
    char *name; 
    char *surname; 
    char *UUN; 
    char *department; 
    char gender; 
    int age; 
} student_t; 

int main() { 
    int i; 
    student_t stdt[6]; 
    stdt[0]={"John","Bishop","s1234","Inf",'m',18}; 
    stdt[1]={"Lady","Cook","s2345","Eng",'f',21}; 
    stdt[2]={"James","Jackson","s33456","Eng",'m',17}; 

    for(i=3;i<6;i++) { 
     printf("First name: \n"); 
     scanf("%s",stdt[i].name); 
     printf("Last name: \n"); 
     scanf("%s",stdt[i].surname); 
     printf("UUN: \n"); 
     scanf("%s",stdt[i].UUN); 
     printf("Department: \n"); 
     scanf("%s",stdt[i].department); 
     printf("Gender (m/f): \n"); 
     scanf("%c",stdt[i].gender); 
     printf("Age: \n"); 
     scanf("%d",stdt[i].age); 
    } 
    return 0; 
} 
+0

값이 실제로 입력되었는지 확인하려면 각 scanf() 호출의 반환 값을 확인해야합니다. – user3629249

+1

각 scanf() 형식 문자열은 선행 공백을 포함해야하므로 '\ n'과 같은 사용되지 않은 공백이 사용됩니다. 그렇지 않으면 scanf()가 일부 값을 입력하지 않고 중단 될 수 있습니다. – user3629249

답변

8

당신이 창조의 시점에서 그것을하지 않으면 당신은 "초기화"아니에요 : 여기

는 지금까지 코드입니다. 다음과 같이 할 수 있습니다.

student_t stdt[2] = { {"John", "Bishop", "s1234", "Inf", 'm', 18}, 
         {"Lady", "Cook", "s2345", "Eng", 'f', 21} 
        }; 

배열의 각 구성원에 대한 값을 명시 적으로 제공하지 않는 것이 좋습니다. 명시 적으로 초기화하지 않은 멤버의 경우 포인터 멤버는 암시 적으로 NULL으로 초기화되고 숫자 멤버는 암시 적으로 0으로 초기화됩니다. 즉,이 :

student_t stdt[4] = { {"John", "Bishop", "s1234", "Inf", 'm', 18}, 
         {"Lady", "Cook", "s2345", "Eng", 'f', 21} 
        }; 

이 동등 다음과 같이

호기심 들어
student_t stdt[4] = { {"John", "Bishop", "s1234", "Inf", 'm', 18}, 
         {"Lady", "Cook", "s2345", "Eng", 'f', 21}, 
         {NULL, NULL, NULL, NULL, 0, 0}, 
         {NULL, NULL, NULL, NULL, 0, 0} 
        }; 

이러한 규칙은 C 표준에서 파생. C11 섹션 6.7.9.21에서

:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

와 "정적 저장 기간이 객체와 같은"에 대한

우리가 제 6.7.9.10 있습니다

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

struct은은 " 위의 세 번째 글 머리의 의미에서 "집계"하십시오. 당신은 당신이 C99 '복합 리터럴'를 사용하는 경우 쓴 거의 무엇을 할 수

+0

그래서 나는 stdt [6]를 말할 수 있습니다. 단지 3 개의 요소 만 말하면서 여전히 다음 3을 사용자 입력과 함께 넣을 수 있습니까? 그것은 메모리의 필수 슬롯을 지정하기 때문에, 맞습니까? – pixelfigure

+0

네, 그렇습니다. 명시 적으로 값을 제공 할 필요는 없습니다. –

+0

대단히 감사합니다! – pixelfigure

2

:

stdt[0] = (student_t){ "John", "Bishop", "s1234", "Inf", 'm', 18 }; 
stdt[1] = (student_t){ "Lady", "Cook", "s2345", "Eng", 'f', 21 }; 
stdt[2] = (student_t){ "James", "Jackson", "s33456", "Eng", 'm', 17 }; 

그러나,이 배열을 초기화하지, 배열에 값을 할당한다. 또한 배열은 main()에 국부적이므로 배열의 다른 세 요소의 값은 불확정합니다. 당신은 그들에 대해 아무 것도 추측 할 수 없습니다.