2012-04-04 2 views
0

나는 약 17 명의 멤버가있는 C 구조체 struct settings currentProfile을 가지고 있으며 모든 멤버를 0으로 초기화하려고합니다. 내가 컴파일러가 에로에게 Expected an expressionInitializing C struct 예상 식

암의 I를 제공이 라인에서 currentProfile = {0}

를 사용

제로로 모든 회원을 설정하려면 (나는 형식 정의 구문 동네 짱 - 올바른 구조체의 구문과 함께 모두이 시도했다) 올바르게 초기화 하시겠습니까? 감사합니다.

+2

가 전시 몇 가지 코드를 보여주십시오 오류. –

+0

이 개념은 KN R book에 명확하게 언급되어있다. –

+0

@MichaelFoukarakis ''settings currentProfile, newProfile void initProfile (void) { currentProfile = {0}; }'' – Toby

답변

6

초기화가 아닌 (잘못된) 할당을하고 있습니다. 모든 회원이 0로 설정된

은 구조체 객체를 초기화하려면 :

struct settings currentProfile = {0}; 

가 선언 후 0에 구조체 객체의 멤버를 설정하려면

memset(&currentProfile, 0, sizeof currentProfile); 
+1

동적으로 할당 된 지적 멤버는 메모리 누수를 피하기 위해'memset' 연산 전에'free' 될 필요가 있습니다 . – moooeeeep

+0

@moooeeeep, 초기화에 문제가 없습니다! – Shahbaz

+0

@Shahbaz하지만 나중에 할당 할 때 문제가 될 수도 있습니다. – moooeeeep

1

memset (pointer_to_struct, 0, size_of_struct);

#include <string.h> 

struct settings currentProfile; 
memset(&currentProfile, 0, sizeof(struct settings)); 
+0

동일한 작업을 수행했지만 오류가 발생했습니다. 아래 코드를 찾으십시오. #include #include using namespace std; 구조체 abc {int x; int y;}; 구조체 abc xyz; int main() { memset (& xyz, 1, sizeof (struct xyz)); cout << xyz.x; // 가비지를 제공합니다 return 0;} –

+0

"나는 C 구조체를 가지고 있습니다 ..."라고 말했습니다. 귀하의 코드는 C++입니다. – jacekmigacz

+0

C 코드 찾기 #include #include // using namespace std; 구조체 abc {int x; int y;}; 구조체 abc xyz; int main() { memset (& xyz, 1, sizeof (struct abc)); // memset (& xyz, 1, sizeof (struct xyz)); // 불완전한 타입의 'struct xyz'에 'sizeof'의 잘못된 응용 프로그램을 제공합니다. printf ("xyz.x = % d", xyz.x); // 쓰레기를 낸다 return 0;} –