2013-07-13 2 views
0
#include <stdio.h> 
#include <stdlib.h> 
void f(struct emp); 
struct emp{ 
char name[20]; 
int age; 
}; 
int main(){ 
    struct emp e = {"nikunj", 23} ; 
    f(e); 
    return 0; 
} 

void f(struct emp e){ 
    printf("%s %d\n", e.name, e.age); 
} 

구조체의 선언 순서는 중요하지 않습니까? 위의 코드를 실행

[email protected]:~$ gcc hello2.c -o main.out 
hello2.c:3:15: warning: ‘struct emp’ declared inside parameter list [enabled by default] 
hello2.c:3:15: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default] 
hello2.c: In function ‘main’: 
hello2.c:10:2: error: type of formal parameter 1 is incomplete 
hello2.c: At top level: 
hello2.c:14:6: error: conflicting types for ‘f’ 
hello2.c:3:6: note: previous declaration of ‘f’ was here 

그러나이 책이 당신의 C의 실력을 테스트 프로그램의 프로토 타입 선언과 구조체 선언의 순서는 중요하지 않습니다 말한다 다음과 같은 오류를 제공합니다. 주문이 중요한지 아닌지 묻고 싶습니다.

답변

4

예 주문이 중요합니다.

f의 함수 프로토 타입 앞에 struct emp의 정의가 나타나도록 코드 순서를 변경하십시오. 이 그들을 통해 읽기 처음 인 경우

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

struct emp{ 
    char name[20]; 
    int age; 
}; 

void f(struct emp); 

... 

GCC는 실제로 당신이 잘못된 순서로 일을했던 사실을 말하려고한다, 그러나 컴파일러 메시지는 약간 혼란이다.

이 두 경고 :

hello2.c:3:15: warning: ‘struct emp’ declared inside parameter list [enabled by default] 
hello2.c:3:15: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default] 

는 '구조체 EMP'의 유형이 파일의 라인 (3) 컴파일 시간 GCC 알려진되지 않았 음을 나타냅니다. 컴파일러는 일반적으로 알 수없는 형식 인 &을 알 수 없으므로 대부분 struct emp을 어떻게 선언 할 지 모르기 때문에 거의 항상 추측합니다.

이 오류 :

hello2.c:10:2: error: type of formal parameter 1 is incomplete 

는 GCC는 (잘못)가 3 행의를 컴파일 할 때 추론하는 형식 매개 변수 유형과 다른 실제 매개 변수 유형과 기능 'F'를 호출하는 것을 시도하고 있음을 나타냅니다 파일.

이 오류와 관련된 참고 :

hello2.c:14:6: error: conflicting types for ‘f’ 
hello2.c:3:6: note: previous declaration of ‘f’ was here 

라인 (14)의 형식 매개 변수 유형 (당신이 라인에 선언 struct emp 이제 유형을 것으로 알려져있다 (7)을 통해 4) 형식 매개 변수와 일치하지 못했음을 나타냅니다 gcc (3 번째 줄에 잘못 추측)를 입력하십시오.

결론 : 모든 유형을 참조하는 프로토 타입보다 먼저 정의해야합니다. 당신이

typedef struct { 
    char name[20]; 
    int age; 
} emp_t; 

을 사용 그리고 당신은 다음 코드를 통해 emp_t보다는 struct emp를 사용할 수 있는지

당신은 또한 당신의 코드를 찾을 수 있습니다 더 많은 읽을 수 있습니다. 또 다른 옵션이있다

0

-이 변화가 너무 그것을 수정합니다 :

#include <stdio.h> 
#include <stdlib.h> 
struct emp; /* <--- add this line */ 

void f(struct emp); /* <-- now this refers to that */ 
struct emp{  /* <-- and this defines the same thing */ 
char name[20];  /* and you didn't need to move things around. */ 
int age; 
}; 

모든 순서 문제를 해결하기 위해 항상 쉬운 일이 아닙니다 복잡한 프로젝트에서이 도움이 될 수 있습니다.

f가 실제로 f (struct emp *) - f (struct emp)가 아닌 경우 구조체 레이아웃의 정의를 포함하지 않고 f()를 정의 할 수 있습니다. 컴파일러는 이름이 붙지 만 정의되지 않은 구조체에 대한 포인터를 사용하여 작업 할 수 있기 때문에 (해당 항목을 저장하거나 반환하거나, 다른 함수로 전달하거나, NULL 또는 다른 포인터와 비교합니다 똑같은 것 ... 다른 포인터 타입으로 캐스팅해라.) - 그러나 p가 불특정 구조체에 대한 포인터라면 sizeof (* p)에 대해서 포인터 연산이나 멤버에 접근 할 수 없다. . 컴파일러에서 알려 드리겠습니다 :-)

관련 문제