struct node *ptr; 을 사용하는 이유?

hurryon의 이미지

아직은 포인터에 대해서 가물가물한 상태입니다. 연결리스트 소스을
보고 있는데 다음과 같은 것이 나옵니다.

#include <stdio.h>
#include <string.h>

struct _node
{
    char name[10];
    int data;
    struct node *next;
};

typedef struct _node node;
typedef node *ptr;

int main()
{
    ptr haha;
    
    haha->data = 1;

    printf("%d\n", haha->data);
}

위의 소스에서

typedef struct _node node; 는 struct _node 을 줄여서 node 라고
사용하기 위해서 위와 같이 쓴다고 이해하고 있습니다. 그런데

typedef node *ptr;

는 왜 사용하는지요? 왜 이렇게 사용하는지 알고 싶습니다.

pynoos의 이미지

typedef 라는 것이 조금 복잡해지기 시작하면, 이해하기 어려운 경우가 있지요.

그것은 아마 #define 문과 조금 다르다에서 출발해서 그럴 것입니다.

하지만, 많은 책들이 설명하는 것 처럼 typedef는 define 문과 비슷한데서 출발하면, 문제가 발생합니다.

#define uint unsigned int

typedef unsigned int uint;

기능이 비슷하기때문에 같이 나열하고 설명하면, 그럴듯해 보입니다

"순서를 바꾸어 표현하는 차이 어쩌고 저쩌고..."

하지만 typdef는 그렇게 해석하는 것이 아니라 제가 보기엔...

"지금 선언하는 것은 변수가 아니다." 로 해석해야 올바른 설명방법입니다.

int (*sig_func)(int);

이렇게 씌여진다면 이것은 함수 포인터를 선언하는 것이죠..
즉 최종 관심대상인 변수 sig_func 를 선언하는 것입니다.

하지만..

typdef int (*sig_func)(int);

라고 앞에 typdef가 씌여진다면, 타입으로서의 sig_func를 선언하는 것입니다.

typedef node *ptr;

이 경우에는

node * 형의 ptr 변수를 선언하는 대신 ptr 타입을 선언하는 것이겠지요.

아무리 복잡해도 일단 typedef를 떼고 변수선언이라 생각하고 보신후에,
나중에 그것이 "변수가 아니라, 타입이다" 라고 생각하시면됩니다.

wind772의 이미지

typedef struct _node node;
typedef node *ptr;

즉,
typedef struct _node *ptr;

현재 예제로 올리신 소스에는 사용하지 않았지만 나중에 노드 포인터 변수를 만들때 유용하게 사용될겁니다..^^

struct _node * HEAD;
node *HEAD;
ptr HEAD;

다 같은거겠죠? ^^
(답변이 될런지...ㅡ_ㅡa)

===================================================
중요한건 얼마나 아느냐가 아니라 그것에 대한 열정이다.

jemiro의 이미지

typedef를 사용해서 예제 코드를 다시 정리해보았습니다.
프로그램 자체는 똑같지만, typedef 를 왜써야 하는지
차이를 느낄실수 있을지도..?

#include <stdio.h>
#include <string.h>

typedef struct _node   node;
typedef node               *node_ptr;

struct _node
{
    char         name[10];
    int            data;
    node_ptr  next;
};

int main()
{
    node_ptr    head_node;

    head_node = (node_ptr) malloc(sizeof(node));
    if (!head_node) {
         return -1;
    }    

    strncpy(head_node->name, "hello",  sizeof(head_node->name) - 1);
    head_node->data = 1;
    printf("%s(%d)\n", head_node->name, head_data);

    return 0;
}
김충길의 이미지

hurryon wrote:
아직은 포인터에 대해서 가물가물한 상태입니다. 연결리스트 소스을
보고 있는데 다음과 같은 것이 나옵니다.

#include <stdio.h>
#include <string.h>

struct _node
{
    char name[10];
    int data;
    struct node *next;
};

typedef struct _node node;
typedef node *ptr;

int main()
{
    ptr haha;
    
    haha->data = 1;

    printf("%d\n", haha->data);
}

위의 소스에서

typedef struct _node node; 는 struct _node 을 줄여서 node 라고
사용하기 위해서 위와 같이 쓴다고 이해하고 있습니다. 그런데

typedef node *ptr;

는 왜 사용하는지요? 왜 이렇게 사용하는지 알고 싶습니다.

위 코드에서 haha는 포인터입니다. 할당된 공간이 없기때문에
haha = (ptr *)malloc(sizeof (node));
한다음에 할당해야 될듯..

ps. 아는 문제였나요?.. 잘못 사용한듯 싶어서요..

screen + vim + ctags 좋아요~

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.