2 Replies - 356 Views - Last Post: 05 July 2013 - 04:45 PM Rate Topic: -----

#1 Emon_MQ  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 37
  • Joined: 06-August 09

Problem with char array field

Posted 05 July 2013 - 03:06 PM

I am just making a singly linked list with only front insertion,when I make the field id ineger it works fine but when its a char array my program crashes,could anyone suggest what's wrong here?
here is the code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct list
{
  char id[20];
  
  struct list *next;     
};

typedef struct list node;
void  insertNode(node **head,char val[]);
void display(node *head);

int main()
{
 node *one;
 one=NULL;
 insertNode(&one,"A");
 insertNode(&one,"b");
 
 
 display(one);
 system("pause");
 return 0;
   
}
void  insertNode(node **head,char val[] )
{
  node *newNode;
  newNode=(node*)malloc(sizeof(newNode));
  strcpy(newNode->id,val); 
      
      
   
  if((*head)==NULL)   
  {  
    (*head)=newNode;
    (*head)->next=NULL;
  }
    
                  
  else if((*head))
  {
    
      newNode->next=(*head);
      (*head)=newNode;                  
  }
    
}
void display(node *head)
{   
  node *cur=head;
  while(cur!=NULL)
  {
    printf("%s->",cur->id);
    cur=cur->next;              
  }   
}





Is This A Good Question/Topic? 0
  • +

Replies To: Problem with char array field

#2 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1432
  • View blog
  • Posts: 4,968
  • Joined: 19-February 09

Re: Problem with char array field

Posted 05 July 2013 - 04:11 PM

Hi, newNode is a pointer so sizeof here is the size of a pointer which is smaller than the structure.

31	  newNode=(node*)malloc(sizeof(newNode));




31	  newNode = (node*) malloc( sizeof(node) );




struct list is confusing because it is not a list but a node.
Was This Post Helpful? 1
  • +
  • -

#3 Emon_MQ  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 37
  • Joined: 06-August 09

Re: Problem with char array field

Posted 05 July 2013 - 04:45 PM

Thanks a lot for the help..now it works :)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1