Strange behavior of "node" - c

I am confused! Trying to create dynamic linked list and want to assign header by "malloc" function. From my code below compiler gives 2 error:
in main: [Error] node' undeclared (first use in this function) and
**In functionnewnode':** [Error] `node' undeclared (first use in this function)
#include <stdio.h>
#include <stdlib.h>
struct node{
int a,b,c,d;
struct node *next;
};
struct node * newnode(int, int, int, int);
int main(){
struct node *header;
header=(struct node *)malloc(sizeof(node));
int a,b,c,d;
a=11;
b=2;
c=4;
d=5;
header->next=newnode(a,b,c,d);
printf("\n\n");
system("PAUSE");
return 0;
}
struct node * newnode(int aa, int bb, int cc, int dd)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(node));
temp->a =aa;
temp->b =bb;
temp->c =cc;
temp->d =dd;
temp->next=NULL;
return temp;
}
I appreciate any advice! thank you!

There is no type node. You have type struct node and that's the one you need to pass to the sizeof operator.

Firstly, as #icepack already noted, the type is named struct node, not node. So, sizeof(node) does not compile. You meticulously used struct node everywhere in your code except in those two spots with sizeof.
Secondly, consider using the
T *p = malloc(n * sizeof *p); /* to allocate an array of n elements */
idiom for memory allocation. E.g. in your case
temp = malloc(sizeof *temp);
I.e. don't cast the result of malloc and prefer using sizeof with expressions, not with type names. Type names belong in declarations. The rest of the code should be as type-independent as possible.

As mentioned by previous answers, you have to use struct node when referencing to your structure.
However if you just want to use the declarative name node you can do as following:
typedef struct _node{
int a,b,c,d;
struct _node *next;
} node;
Here you do not need to use struct before you reference a node
Edit: wrong syntax

Related

Creating a pointer directly from a typedef struct definition

I want to check what the following code means. I think I am creating a pointer to a list of pointers to adjlistnode structures but I'm not sure.
Here is the code:
typedef struct adjlistnode {int node; int cost; struct adjlistnode *next;}
**AdjMatrix;
I'm confused as to what **AdjMatrix actually is. Like I said above, I think it is a pointer to a list of pointers to adjlistnode structures but I'm not sure. Am I right in my assumption?
The rules around a typedef can be simplified to the following generalization: if you have any valid variable declaration in C (without a storage class such as extern, static or register, etc.), then strapping a typedef at the front turns the variable name into a new type name, based on the type of the variable.
So here, without the typedef:
struct adjlistnode {int node; int cost; struct adjlistnode *next;}
**AdjMatrix;
AdjMatrix is variable of type pointer to pointer to struct adjlistnode.
But in your post, because of the typedef, AdjMatrix is a name for the type pointer to pointer to struct adjlistnode.
I think it is a pointer to a list of pointers to adjlistnode structures
No, it isn't.
AdjMatrix becomes a type representing a pointer to pointer to struct adjlistnode
As an example it can be used like:
AdjMatrix p = NULL; // p is now a pointer to pointer to struct adjlistnode
The code seems to be for building a linked list and AdjMatrix seems to be a short hand for referring to a pointer to the head pointer. It could be used like:
void addNode(AdjMatrix pHead, int node, int cost)
{
struct adjlistnode *tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->cost = cost;
tmp->next = *pHead;
*pHead = tmp;
}
void deleteNode(AdjMatrix pHead)
{
if (*pHead)
{
struct adjlistnode *tmp = *pHead;
*pHead = tmp->next;
free(tmp);
}
}
int main(void) {
struct adjlistnode *head = NULL;
// Add nodes
addNode(&head, 1, 2);
addNode(&head, 3, 4);
addNode(&head, 5, 6);
// ... use the list
// Delete nodes
while(head) deleteNode(&head);
return 0;
}
Notice that typedef of pointers is often considered bad practice. Instead it would be better to do:
typedef struct adjlistnode {int node; int cost; struct adjlistnode *next;} AdjMatrix;
and use it like:
void addNode(AdjMatrix **pHead, int node, int cost)
to make it clear the pHead is a pointer to pointer to AdjMatrix
From typedef [emphasis added]:
typedef is a reserved keyword in the C and C++ programming languages. It is used to create an alias name for another data type. 1 As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, but is just as common in providing specific descriptive type names for integer data types of varying lengths.
The AdjMatrix is an alternative name of struct adjlistnode ** type, which is a pointer to pointer to struct adjlistnode.
You can use it to declare variables like this:
AdjMatrix pp_st_adjlistnode;
which means pp_st_adjlistnode is a pointer to pointer to struct adjlistnode.

How to make library for linked-list functions

I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file
#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
int c = 0;
while(head != NULL){
if(head->data == n) c+=1;
head = head->next;
}
return c;
}
But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?
structure is declared in the main function as
struct node{
int data;
struct node *next;
}
Prior to using objects (you use it, when have access to its members) you must completely define them. So, to use struct node, declare it before its first appearance in the source code. It's the rule of C programming language.
Put the declarations into header file and include the file into source files if you want to create useful libraries, e.g.:
...
struct node
{
...
};
int count(struct node *head, int n);
...
Continuing from the comment, in your code, the compiler does not know what node is because you have not provided its declaration. You can provide a declaration including a typedef for convenience. The following code declares a typedef to struct _node {...} as node; and then declares two nodes (statically for simplicity reasons), iterates over the list, outputting the data values and then ends, e.g.
#include <stdio.h>
typedef struct _node {
int data;
struct _node *next;
} node;
int main (void) {
node n1 = {.data = 1},
n2 = {.data = 2, .next = NULL};
n1.next = &n2;
/* iterate over list outputting data values */
for (node *n = &n1; n != NULL; n = n->next)
printf ("%d\n", n->data);
return 0;
}
Example Use/Output
$ ./bin/llstatic
1
2
As mentioned, you can create a header file for your list and include your declaration of struct _node and the typedef there, or if you simply use node within this source-file, you can declare it here. Let me know if you have further questions.
The compiler tells you it does not recognize struct node. You need to Declare it first. Something like struct node; (decleration) or struct node{...}; (definition) and the error should go away. If you have already declared it in another file header.h, just add #include "header.h" in the start of your code
Since you want struct node to contain a field called data, you need to add it when you define the struct:
struct node{
int data;
}

What's the use of 'typedef in C'?

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.)
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.
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).

Difference between these c struct declarations?

I have a code looking like this :
struct point {
int a;
int b;
}
which can be further used like this :
struct point p;
p.x = 10;
p.y = 5;
now I came to know that this can also be written like this :
typedef struct{
int x;
int y;
} point;
and can be used as point p
The confusion started when I started learning linked-list, this is the code I saw.
typedef struct node {
int val;
struct node * next;
} node_t;
I have a couple of questions:
If we can define the struct by simply using typedef struct { ... } node whats the use of writing typedef struct node {.....
The node_t at the end of the code is really confusing because from my understanding it has already defined a type node so we can call node x to create a node , then what's the need of the node_t or basically writing anything after the } what it means ?
shouldn't this work ?
typedef struct {
int val;
struct node * next;
} node;
If we can define the struct by simply using typedef struct { ... } node whats the use of writing typedef struct node {.....
The node_t at the end of the code is really confusing because from my understanding it has already defined a type node so we can call node x to create a node , then what's the need of the node_t or basically writing anything after the } what it means ?
In C, structures can have both tag and a typedef name. In the structure declaration:
typedef struct node {
int val;
struct node * next;
} node_t;
node is a tag and node_t is typedef name. Latter you can declare your structure variable either by using tag or typedef name.
struct node *new_node; // OK
node_t *head; // OK
In fact, the tag and typedef name can even be same, although that's not required:
typedef struct node {
int val;
struct node * next;
} node;
shouldn't this work ?
typedef struct {
int val;
struct node * next;
} node;
No. This will not work . Why?
The reason is that, when a structure has a member that points to the same kind of structure, as node does, we are required to use a structure tag. Without the node tag, we would have no way to declare the type of next.
Suggested reading: As Op is asking for good resource on data structure. Here you can go:
Tutorial: Introduction to Data Structures.
Book: Classic Data Structures.
The third block of code, which you seem to have a question about, has a redundant identifier.
typedef struct node {
int val;
struct node * next;
} node_t;
is identical to
struct node{
int val;
struct node * next;
};
typedef struct node node_t;
They're identical, but merged into the same line. The syntax around a typedef is
typedef [original name] [new name];
Normally, when we typedef a struct, the ONLY way to reference it afterwards would be the typedeffed name (in the first code example, you could only access it by node_t) while a slightly more redundant declaration allows for accessing by the "struct node" variable type too.
To answer your other question the node_t that confused you is what you can refer to the struct as... for example
node_t node1;
struct node node2;
Are the two valid declarations for a node struct.
Here, you can also use 'struct p' by typedefing it using 'struct p typedef P;'. It sometimes makes me confused when typedef a complex function pointer.
I don't know the reason why the C std. support such a syntax sugar.
Here is my explanation.
struct
{
int i;
};
declares an unnamed structure and apparently there is no real usage of this. Please correct me if I am wrong.
struct
{
int i;
} T;
now T is an object in the given scope and type is unnamed.
struct TT
{
int i;
} T;
declares a structure TT and an object T. You can use TT to create more objects. The best way to think about this is, just consider struct TT{ int i} as a single type such as double.
typedef struct TT
{
int i;
};
has the same meaning as (at least in nowadays compiler. I'm not sure about the older ones)
struct TT
{
int i;
};
and
typedef struct
{
int i;
} TT;
declares a type TT (not an object) for the given structure as you are using typedef int Int;
Hope this resolves the mess.

Unable to get this data structure to work (newbie)

I'm pretty new to C, and I've been trying to make a program with this data structure:
struct node {
char command[100];
char prereq[100][80];
char *targ;
int isUpdated;
} Node;
However, whenever I try to implement it in the code, like this:
Node n = malloc(sizeof(*n));
I get compiler errors such as "nmake.c:13:31: error: unknown type name ‘Node’".
I've tried code such as:
typedef struct node *Node;
with similar results. What's wrong?
I think you are confused about what typedef does.
A declaration such as this one:
struct node { ... };
will define a type named struct node. Do not forget the word struct! If you say just node it will mean nothing (note that this is different in C++).
So now to create a local variable you do:
struct node x;
And to do a dynamic one:
struct node *px = malloc(sizeof(struct node));
Now, if you want to make an alias to the type, you use the same exact syntax than to create a variable, but you write typedef at the beginning of the declaration:
typedef struct node Node;
Or if you prefer the pointer type:
typedef struct node *PNode;
Then to create variables:
Node a;
Node *b = malloc(sizeof(Node));
PNode c = malloc(sizeof(Node)); //do not use sizeof(PNode) as it is useless here
Some people, as #WhozCraig says in the comments, and you seem to intend in the original code prefer to use the declaring variable for sizeof instead of the type:
Node *b = malloc(sizeof(*b));
PNode c = malloc(sizeof(*c));
Actually there is no real difference, other than the style, so pick your favorite!
Note that when defining the original struct you can use the same declaration to create variables or typedefs, but not both:
struct node { ... } a; //a is a variable
typedef struct node {...} b; //b is a type
Some people like to force the syntax and do something like this:
typedef struct node {...} Node, *PNode; //tree types in one line!
but personally I find this practice a bit dumb: don't typedef a pointer unless you want to hide the fact that it is a pointer.
What you probably want is:
typedef struct _node {
char command[100];
char prereq[100][80];
char *targ;
int isUpdated;
} Node;
/*
* This defines a structure named _node.
* To use it, you must add struct everytime, for instance:
* struct _node foo;
*
* It also defines a typedef named Node which is a synonym to struct _node - Node
*/
Node *n = malloc(sizeof(*n));
/*
* Because we want to dynamically allocate we need a pointer, so we declared it as a Node *
*/

Resources