My execution's name is test4.
Input:
$ ./test4 cccc zz abcdef0123456789 aaabbbcccddd
I expect to create a linked list of type char* as follow:
---> 12:aaabbbcccddd ---> 12:abcdef0123456789 ---> 2:zz ---> 4:cccc
each node has the form of "n:a" (n is the length of string a, n <= 12, if the length of a is more than 12 then n = 12)
Below is my code:
struct Node *prepend(struct Node *list, char *s)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
if (node == NULL)
return NULL;
int length_s = strlen(s);
if (length_s > 12)
length_s = 12;
char* temp = NULL;
sprintf(temp,"%d:%s", length_s, s);
strcpy(node->data, temp);
node->next = list;
return node;
}
prepend function links a new node to list
struct Node {
struct Node *next;
char *data;
};
int main(int argc, char **argv)
{
struct Node *list = NULL;
argv++;
while (*argv)
{
list = prepend(list,*argv);
argv++;
}
return 0;
}
Assume all necessary libraries and struct are included, I keep getting a segmentation error when running the code. How do I fix it? I believe the problem is in sprintf but can't figure out why.