2

I'm coding in C language and can't find out what is the error.It keeps telling me that First: in this line

temp = (Node*) malloc(sizeof(struct Node));

the Node is undeclared and first use is in this function.but I think I've declared it before.

Second: in the same line

"expected expression before ')' token"

it points to the (Node*)

and Third :

"expected declaration or statement at end of input."

while it points to the closed } of main.

For the first one I've searched and found out it's because of C89 and I have to declare all the variables at the top of my functions.I did but the error is still there.

here's my code:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h> 
#include <malloc.h>

 struct Node{
    int data;
    struct Node* next;
};

struct Node* head;

void Add(int x){
    struct Node* temp;
    temp = (Node*) malloc(sizeof(struct Node));
    temp -> data = x;
    temp -> next = head;
    head = temp;
}

void print(){
    struct Node* temp;
    temp = head;
    printf("List is:");
    while(temp != NULL){
        printf(" %s",temp -> data);
        temp = temp -> next;
    }
int main(int argc, char **argv)
{

    head = NULL;
    Add(3);
    print();
    return 0;
}

I'm trying to use a linked list.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Saman Nourkhalaj
  • 61
  • 1
  • 1
  • 10
  • 1
    "For the first one I've searched and found out it's because of C89 and I have to declare all the variables at the top of my functions." No you have to declare them before you use them. Same goes for functions. – Emz Dec 20 '15 at 08:54

1 Answers1

8

In your code

 temp = (Node*) malloc(sizeof(struct Node));

should be

 temp = malloc(sizeof(struct Node));

or, for better,

 temp = malloc(sizeof *temp);

eliminating the issue, as you need not to cast the return value of malloc() and family in C..

The error was, however, because you missed the struct keyword there.

To address the third error,

"expected declaration or statement at end of input."

well, you missed the ending } for the print() function.

FWIW, you should always check the validity of the returned pointer by malloc() and family of functions before making use of it.

Having said that,

For the first one I've searched and found out it's because of C89 and I have to declare all the variables at the top of my functions

is not true. Yes, in C89, you needed to declare all the variables at top, but that did not allow you to skip the struct keyword, anyway.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261