Array of structures in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    Array of structures in C

    I'm trying to create a structure which has an integer and a pointer to the same type. So I created a structure of that type but I seem to be printing wrong values.
    Code:
    #include <stdio.h>
    #include <string.h>
    #define max 20
    struct node{
    	int i;
    	struct node *next;
    };
    void print(struct node*);
    
    int main(){
    	struct node* b= (struct node*) malloc(sizeof(struct node));
    	b[0].i = 1;
    	b[0].next = NULL;
    	b[1].i = 2;
    	b[1].next = NULL;
    	struct node *c = (struct node*) malloc(sizeof(struct node));
    	c[0].i = 3;
    	c[0].next = NULL;
    	c[1].i = 4;
    	c[1].next = NULL;
    	b[0].next = c;
    	//print(b);
    	printf("%d %d\n",b[0].i,b[1].i);
    	return 1;
    }
    My ideal output should be
    Code:
    1 2
    but I'm getting
    Code:
    1 3
    I can't figure out why this is happening, please help
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    The malloc's are allocating enough for one node, but the code acts like it's got an array of nodes.

    "b" is one node, "c" is one node. There is no b[1] or c[1]. You should access b using pointer notation and not confuse yourself

    b->i = 1;
    b->next = NULL;

    Comment

    Working...