구조체 함수멤버 사용에 관해서...
글쓴이: kernelbomb / 작성시간: 금, 2004/05/14 - 11:52오전
간단하게 class를 흉내낼려고 따라하고 있는데 세그먼트 폴트가 나네요.
원래 함수에는 init란게 없어서 name 멤버를 초기화 하지 않아 에러가
나는것 같아 init 함수를 넣어주고 초기화 시켰는데도 세그먼트 폴트가
납니다. 왜이러는지 정말 헷갈리네요.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct data { /* 멤버변수 선언 */ int id; char *name; /* 멤버함수 선언 */ void (*init)(struct data *pData); void (*set_name)(struct data *pData, char *newname); char (*get_name)(struct data *pData); void (*clear)(struct data *pData); }; void init(struct data *pData) { pData->id = 0; pData->name = 0l; pData->init = NULL; pData->set_name = NULL; pData->get_name = NULL; pData->clear = NULL; } void set_name(struct data *pData, char *newname) { if (pData->name) { if (strlen(pData->name) < strlen(newname)) { free(pData->name); pData->name = malloc(sizeof(char) * strlen(newname) + 1); } } else { pData->name = malloc(sizeof(char) * strlen(newname) + 1); } strcpy(pData->name, newname); } char *get_name(struct data *pData) { if (pData->name) return pData->name; else return NULL; } void clear(struct data *pData) { pData->id = 0; if (pData->name) { free(pData->name); pData->name = NULL; } pData->get_name = NULL; pData->set_name = NULL; pData->clear = NULL; } int main(void) { struct data aData; /* 구조체 함수포인터에 각 함수의 주소를 대입한다. */ aData.init = init; aData.get_name = get_name; aData.set_name = set_name; aData.clear = clear; aData.init(&aData); aData.id = 100; printf("aData.id = %d\n", aData.id); aData.set_name(&aData, "test"); printf("aData.name = %s\n", aData.get_name(&aData)); aData.clear(&aData); return 0; }
Forums:
aData.init(&aData) 를 호출하고 난 후에 aData
aData.init(&aData) 를 호출하고 난 후에 aData.set_name()을 호출하는군요. 어떤 사태가 벌어질까요? :(
덤으로 pData->name 의 초기값을 0l 이 아닌 NULL로 하는게 읽기 편하지 않을까요?
음...
문자열을 리턴해 줘야 하는데 잘 못 선언했군요.
char (*get_name)(struct data *pData);
이것을
char *(*get_name)(struct data *pData);
으로 바꿔야 합니다. 또한 init()에서는
로 바꿔야 하고 main()에서의 init 호출은 맨 위에서 해야합니다.
H/W가 컴퓨터의 심장이라면 S/W는 컴퓨터의 영혼이다!
댓글 달기