link list

Hi i am trying to make a link list.The data to the link list will be added from the command line . example of a command line will --- I 45 here 45 is the data to be added.(time)

the following is my working

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>

// get include from current directory.

#define UINT unsigned int
using namespace std;

struct item
{ UINT time ; // time in tics which is used to order the list.
UINT id ; // penguin id number.
UINT event ; // event this item describes.
struct item *next ; // pointer to next item in list.
} ;

struct item *head_ptr ;
struct item *work_ptr ;


int main(int argc, char *argv[])
{


for(int i=1; i<argc; i++)
{
if (!strcmp(argv[i],"I"))
{

work_ptr=head_ptr;
head_ptr=(item*)malloc(sizeof(struct item));

strcpy((char*)head_ptr->time ,(char*)argv [i+1] ) ;


cout << head_ptr ->time << endl;

head_ptr -> next = work_ptr;
}


return 0;
}

but at the strcpy((char*)head_ptr->time ,(char*)argv [i+1] ) ; i get SEGMENTATION FAULT i dont know whats wrong with my code please help

can you please write the code inside code tag. its very difficult to read the code
Last edited on
Maybe use more braces... And make it a pointer... Not really sure... (char*)&(head_ptr->time)
Last edited on
struct item
{ UINT time ; // time in tics which is used to order the list.
UINT id ; // penguin id number.
UINT event ; // event this item describes.
struct item *next ; // pointer to next item in list.
} ;

struct item *head_ptr ;
struct item *work_ptr ;


int main(int argc, char *argv[])
{


for(int i=1; i<argc; i++)
{
if (!strcmp(argv[i],"I"))
{

work_ptr=head_ptr;
head_ptr=(item*)malloc(sizeof(struct item));

strcpy((char*)&(head_ptr->time) ,(char*)&(argv [i+1]) ) ;


cout << head_ptr ->time << endl;

head_ptr -> next = work_ptr;
}

i get some random number for cout<< head_ptr->time when i did that
It looks like you want to concert a string to a integer... Use atoi to do that:

head_ptr->time = atoi(argv[a+1]);
Last edited on
no i want to copy the command line parameter and store it in the link list
Ah.. I see... Now you have only 1 value but you plan on filling the complete struct? Do you want to save the number 45 or the representation of the characters '4' and '5'?
number 45
Then you should use atoi...

head_ptr->time = atoi(argv[a+1]);
yeah that worked thanks
Topic archived. No new replies allowed.