-2

There are 3 versions of a header file.

version 1:

typedef struct node
{
    void* dataPtr;
    struct node* link;
} NODE;

version 2: without old type name 'node' (typedef oldTypeName newTypeName)

typedef struct
{
    void* dataPtr;
    struct* link;
} NODE;

version 3: without typedef

struct
{
    void* dataPtr;
    struct* link;
} NODE;

According to C : typedef struct name {...}; VS typedef struct{...} name;, version 1's defining 'node' is superfluous and I changed it to version 2 and it worked fine.

According to this answer again, when not using 'typedef', one cannot reuse 'NODE'.

However, codes that use this version 3 header file worked just fine. (NODE was used two three times.)

This is the code:

/* Create a list with two linked nodes.*/
#include <stdio.h>
#include <stdlib.h>
#include "version3.h"                      //Header file

int main (void)
{
//Local Definitions
    int* newData;
    int* nodeData;
    NODE* node;

// Statements
    newData = (int*)malloc (sizeof (int));
    *newData = 7;
    node = createNode(newData);

    newData = (int*)malloc (sizeof (int));
    *newData = 75;
    node->link = createNode(newData);

    nodeData = (int*)node->dataPtr;
    printf ("Data from node 1: %d\n", *nodeData);

    nodeData = (int*)node->link->dataPtr;
    printf ("Data from node 2: %d\n", *nodeData);
    return 0;
}       //main

What's the use of 'typedef' in this situation? (assuming that here I reused NODE. -> if this assumption is not true, please tell me why. I'm not familiar with C language.)

Community
  • 1
  • 1
Hee Kyung Yoon
  • 253
  • 1
  • 4
  • 14
  • 1
    typedef defines a new type, which you can use for more than one instance. Did you try searching for other answers to this question here? – Dronz Mar 15 '15 at 05:07
  • 1
    The line `struct* link;` doesn't compile. Neither version 2 nor version 3 works because neither one compiles. – user3386109 Mar 15 '15 at 05:08

2 Answers2

3

The following code does not create a type. It creates an object named NODE that has an anonymous struct as it's type.

struct {
    void* dataPtr;
    void* link;
} NODE;

int main() {
}

I find it difficult to believe that the code in your question compiles.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

typedef is used to give a new name to a type. When your third version of struct is used then it just declare NODE of type struct{ void* dataPtr; struct* link;}. Now what would you do if you have to declare another variable of same type as of NODE? There is only one option, you have to declare it along with NODE otherwise they are incompatible.
Two structure are compatible if they are declared at same time or if they are declared using structure tag or the same type name (using typedef).

haccks
  • 104,019
  • 25
  • 176
  • 264