What's wrong of the the code for making a list??

M

Mars

I followed the reference about ADT,
and wrote something like below....


#include <stdio.h>

/* I intend to make this a list */
struct node_s
{
int x;
struct node_s * next;
};

typedef struct node_s node;

int main(void)
{
node anode;

/* is this corrent? */
anode.next=(node *)malloc(sizeof(node));

anode.next.x=1;

return 1;
}


The code gives

"error: request for member 'x' in something not a structure or union"
 
P

pete

Mars said:
I followed the reference about ADT,
and wrote something like below....

#include <stdio.h>

/* I intend to make this a list */
struct node_s
{
int x;
struct node_s * next;
};

typedef struct node_s node;

int main(void)
{
node anode;

/* is this corrent? */
anode.next=(node *)malloc(sizeof(node));

anode.next.x=1;

return 1;
}

The code gives

"error: request for member 'x' in something not a structure or union"


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

struct node_s
{
int x;
struct node_s *next;
};

typedef struct node_s node;

int main(void)
{
node anode;

anode.next = malloc(sizeof *anode.next);
anode.next -> x = 1;
printf("%d\n", anode.next -> x);
free(anode.next);
return 0;
}
 
A

Al Bowers

Mars said:
I followed the reference about ADT,
and wrote something like below....


#include <stdio.h>
You need the header for function malloc.
#include said:
/* I intend to make this a list */
struct node_s
{
int x;
struct node_s * next;
};

typedef struct node_s node;

int main(void)
{
node anode;

/* is this corrent? */
anode.next=(node *)malloc(sizeof(node));

You do not need the cast. Also, check the return value
of function malloc to make sure the allocated occurred.
anode.next.x=1;

anode.next is a pointer. You either need to use the *
operator or the -> operator.
(*anode.next).x = 1;
or
anode.next->x = 1;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,160
Messages
2,570,889
Members
47,420
Latest member
ZitaVos505

Latest Threads

Top