For inserting a node at the beginning y the foll code wont work?

struct node
{
int data;
struct node *-next;
}*head,*run,*ptr;
typedef struct node n;
void create()
{
if(head==NULL)
{
head=n*(malloc(sizeof(n));
}
else
{
ptr=n*(malloc(sizeof(n));
ptr=head;
scanf("%d",&ptr->data);
head=ptr->data;
ptr=ptr->next;
}

Recommended Answers

All 4 Replies

For inserting a node at the beginning y the foll code wont work?

struct node
{
int data;
struct node *-next;
}*head,*run,*ptr;

Hey i think you missed out on the erreneous "-" sign behind next in

struct node *-next;

It should be

struct node * next;

And also the malloc is not used like this:

head=n*(malloc(sizeof(n));

it should be as this:

head=(n*)malloc(sizeof(n));

This code does not wont work, you can't compile this code (feel the difference ;)).

struct node *-next; /* Why minus sign? */
typedef struct node n;

Well, you declare n as an alias of struct node type. Why?

void create() {
    ...
}

These function works with declared elsewhere global variables. Why?

ptr=n*(malloc(sizeof(n));
ptr=head;

Let's forget for a minute that n is a structure type, not a number. The 1st statement allocates memory and saves a pointer to the new object in ptr pointer variable. The next statement overwrites this value immediately. Why?

And so on...
It seems you must reread your C textbook right now...

fine tat was a typing mistake... ma doubt is hw 2 proceed..
first i mus allocate memory 4 creating the list right ???
so i did tat..
then the next time head is not null so i must traverse 2 d next node right so i gave such a declaration!!

Lets just take a look at this code:

ptr=n*(malloc(sizeof(n));
ptr=head;
scanf("%d",&ptr->data);
head=ptr->data;
ptr=ptr->next;

You don't need line 1 because you just set it to point to a space of memory that has already been allocated ( head=n*(malloc(sizeof(n)); ). Lines 2 and 3 look alright to me. Line 4 doesn't work (I sure hope that doesn't compile) because head is a pointer (to a struct node) and you are trying to assign to it a plain old integer. Since ptr and head point to the same thing, line 3 takes care of what you want. Line 5 may seem to make sense, but it actually does nothing. At the end of this function call, ptr will be deleted. A few final notes: the first time you call this function, it will only allocate memory, not load any data. And you seem to be missing a closing } for the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.