c언어 구조체 초기화 관련 질문
조회수 2751회
typedef struct PersonArray {
Person people[NUM_USER];
int total_waiting_time;
int total_waiting_people;
}PersonArray;
PersonArray *PeopleArray;
PeopleArray->total_waiting_time = 0;
PeopleArray->total_waiting_people = 0;
전역변수로 설정한 구조체 PersonArray 입니다.
그리고 구조체 포인터로 PeopleArray를 만들고 이 안의 내용을 초기화하기 위해서
PeopleArray->total_waitting_time = 0; PeopleArray->total_waiting_people = 0;
을 했는데 -> 부분에 에러표시가 뜨면서 ';'가 필요합니다 라고 하네요...
제가 구조체안의 변수의 초기화를 잘못된 방법으로 한 건가요?
어떻게 해야 전역변수 구조체를 초기화 할 수 있을까요
그리고
#include <stdio.h>
#include <stdlib.h>=
#define SIZE_QUEUE 100 //the maximum size of the news_queue
#define CAPACITY 6 //the capacity of ZNN.com (per sec)
#define NUM_USER 20 //the number of users
#define NUM_LOOP 100 //the number of loops
//ContentFidelity is one of the types: video, image, text
typedef enum { Video, Image, Text } ContentFidelity;
typedef struct {
unsigned int requestedBy;
ContentFidelity fidelity;
} news; // 사용자 8이 동영상을 요청하면, 요청한 뉴스 콘텐츠를 (8,video)로 출력한다
typedef struct {
news queue[SIZE_QUEUE];
unsigned int front;
unsigned int rear;
} Queue; // 사용자가 요청한 뉴스 콘텐츠 쌓는 큐
Queue *news_queue;
ContentFidelity currentFidelity = Video; // 처음 콘텐츠는 동영상
/**/
typedef struct Person { // 사용자 구조체(콘텐츠 개수와 대기시간 정보)
int content_num; // 요청한 콘텐츠 전체개수
int receive_content; // 수신받은 콘텐츠 전체개수
int waiting_time; // 총 delay time
int content_score; // 수신받은 콘텐츠들의 총점수
}Person;
typedef struct PersonArray { // 사용자 구조체를 위한 구조체(배열)
Person people[NUM_USER];
int total_waiting_time; // 총 대기시간
int total_waiting_people; // 지금까지 콘텐츠를 요청한 사용자들의 수(중복 가능)
}PersonArray;
PersonArray *PeopleArray;
PeopleArray->total_waiting_time = 0;
PeopleArray->total_waiting_people = 0;
for (int i = 0; i < 20; i++) {
PeoepleArray->people[i].content_num == 0;
PeoepleArray->people[i].receive_content == 0;
PeoepleArray->people[i].waiting_time == 0;
PeoepleArray->people[i].content_score == 0;
}
위 코드에서
for (int i = 0; i < 20; i++) {
PeoepleArray->people[i].content_num == 0;
PeoepleArray->people[i].receive_content == 0;
PeoepleArray->people[i].waiting_time == 0;
PeoepleArray->people[i].content_score == 0;
}
이 부분에서 for구문 자체에 에러표시가 뜨면서 안되는데
혹시 PeopleArray안의 people 구조체 배열안의 값들도 따로 함수를 이용하지 않고
모두 0으로 초기화할 수 있는 방법이 없을까요?
1 답변
-
포인터라는 것의 이해가 필요해보입니다.
그리고 구조체라는 것을 큰 데이터 형식이고 그것을 세분화시킨 타입이라고 이해하면 어떨까요?
PersonArray *ptrPeopleArray;
라는 것은 포인터 ptrPeopleArray라는 것은 PersonArray 형식을 가지고 있는 메모리의 시작 주소입니다.
즉 명시적으로 메모리 주소를 가리켜줘야 합니다. 가리킬 것이 없다면 새로 생성을 하고 그 생성한 것의 주소를 대입해서 가리키도록 해야 합니다.
ptrPeopleArray= (PersonArray*)malloc(sizeof(PersonArray )); // 혹은 PersonArray l_personArray; 같이 스택에 만들고 ptrPeopleArray = &l_personArray; 와 같이 합니다.
위와 같이 해줍니다.
- 할당하는 것을 까먹고 있었군요 ㄷㄷ 감사합니다 서형진 2018.5.3 15:39
- 알려주신 것처럼 malloc을 하려고 하는데 malloc에 빨간줄이 쳐지면서 '상수 식에 함수 호출을 사용할 수 없습니다' 라고 뜨는 것의 원인은 무엇인지 알려주실 수 있나요? 서형진 2018.5.3 15:50
- c/c++ 질문을 올릴때는 사용하는 컴파일러와 버전 및 사용옵션을 함께 명시해줘야 합니다. 일단 해당 오류는 c++이 아니라 c에서 발생할 것 같습니다. 그리고 malloc 로 생성한 변수가 정적인 변수아닌가요? 그렇다면 전역변수로 선언해보세요. 정영훈 2018.5.3 19:51
댓글 입력