파싱해서 파일의 데이터를 읽어올때 연결리스트의 malloc부분 질문입니다.

alsrud의 이미지

load함수를 이용해 파일로부터 연결리스트의 내용을 읽어들일 때
안풀리는 점이 있어 질문 드립니다.
아래와 같이 메인함수에서 load함수를 호출하고
아래 load함수에서 동적할당을 받아 내용을 불러오는 내용인데요ㅜㅜ

아무리 머리를 굴려서 코드를 수정해도 마지막에 암묵적인 tail이 존재하게 됩니다.
이 암묵적인 tail 없이 메모리를 불러오려면 어떤 방식으로 접근을 해야할까요ㅜㅜ?

int main()
{
	char *fname = "address.txt";
	char id[ID_SIZE];
	int i;
 
	struct addr *t;
	struct addr *head; = (struct addr*)malloc(sizeof(struct addr));
 
 
	load_addr(fname, head);
 
        생략
}
 
 
struct addr* load_addr(char *s, struct addr *t)
{
	FILE *fp = fopen(s, "r");
 
	char buf[500];
	char *temp = NULL;
	char *delim = "|\n";
	int i = 0;
 
	if(fp == NULL) { 
		printf("%s\n파일이 존재하지 안습니다.", s);
		return NULL;
	}
 
	while(fgets(buf, 500, fp) != NULL) {
		t->next = (struct addr*)malloc(sizeof(struct addr));
 
		temp = strtok(buf, delim);
		if(i++ == 0)
			strncpy(t->part, temp, sizeof(t->part));
		while(temp != NULL) {
			temp = strtok(NULL, delim);
			if(i == 1) {
				strncpy(t->name, temp, sizeof(t->name));
				i++;
			}else if(i == 2) {
				strncpy(t->position, temp, sizeof(t->position));
				i++;
			}else if(i == 3) {
				strncpy(t->id, temp, sizeof(t->id));
				i++;
			}else if(i == 4) {
				strncpy(t->tel, temp, sizeof(t->tel));
				i++;
			}else if(i == 5) {
				strncpy(t->phone, temp, sizeof(t->phone));
				i++;
			}else if(i == 6) {
				strncpy(t->extension, temp, sizeof(t->extension));
				i++;
			}else if(i == 7) {
				strncpy(t->email, temp, sizeof(t->email));
				i = 0;
			}
		}
 
		t = t->next;
		t->next = NULL;
	}
	fclose(fp);
	return t;
}
raymundo의 이미지

1)

t 포인터 말고 포인터 prev를 하나 더 두어서 현재 t 의 바로 앞 노드를 가리키도록 한 다음에
루프 빠져나온 후에 마지막 tail노드 삭제

free(prev->next);
prev->next = NULL;

2)

카운트 변수를 따로 두어 (지금 보면 i 를 써도 될 듯), 제일 첫 루프에서는 t가 가리키는 노드를 채우고, 그 다음 루프부터는 새 노드를 만들어 채움

while (한줄 읽고) {
    if ( 이번이 첫 번째 루프가 아니면 ) {
        t->next = malloc(...);
        t = t->next;
    }
    이제 buf의 내용을 t에 채운 후
    t->next = NULL;
}

등등의 방법이 있겠네요.

좋은 하루 되세요!

alsrud의 이미지

1)

t 포인터 말고 포인터 prev를 하나 더 두어서 현재 t 의 바로 앞 노드를 가리키도록 한 다음에
루프 빠져나온 후에 마지막 tail노드 삭제

1번으로 해결했습니다 ^^

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.