2
struct node
{
    char *IPArray[100];
    struct node *ptr;
};
typedef struct node NODE;

NODE *head, *first, *temp = 0;

first = 0;

int numofIP;

This is my structure to contain string at every node in a linked list. And numofIP is maximum number of strings or nodes in my linked list.

for(int i=0; i<numofIP; i++)
{
    head  = (NODE *)malloc(sizeof(NODE));
    printf("enter the IP addresses:\n");
    scanf("%s",&head->IPArray[i]);

    if(first != 0)
    {
        temp->ptr = head;
        temp = head;
    }
    else
    {
        first = temp = head;
    }
}

temp->ptr = 0;
temp  = first;

this is how I accept input and store it in every node.

while(temp != NULL)
{
    printf("%d=> ",temp->IPArray);
    temp = temp->ptr;
}

And this is how I print the linked list.

But problem is I get addresses in output. I am not able to figure it out. How to store a string in each node in a linked list?

3
  • char *IPArray[100];char IPArray[100];, scanf("%s",&head->IPArray[i]);scanf("%s", head->IPArray[i]);, printf("%d=> ",temp->IPArray);printf("%s=> ",temp->IPArray); Commented Mar 4, 2016 at 5:40
  • don't cast the result of malloc in C Commented Mar 4, 2016 at 5:43
  • Your character array "char *IPArray[100] "is actually an array of character pointers.It stores character addresses. Commented Mar 4, 2016 at 7:27

2 Answers 2

2

1.Change

printf("%d=> ",temp->IPArray);

to

printf("%s=> ",temp->IPArray);

You have given incorrect format specifier to printf function.

2.Allocate memory for each char* in IPArray.

But, As you have mentioned you need only one string in a node then change char* IPArray[100] to char IPArray[100]

char* IPArray[100] : will create pointers to 100 strings for which you need to allocate memory later on.

char IPArray[100] : will create array of 100 characters in which you can store IP address for particular node and you don't need to allocate separate memory for that.

Sign up to request clarification or add additional context in comments.

Comments

0

Replace your while loop with the following loop.It should work.And dont forget to initialise j=0;

 while(temp != NULL)
{
    printf("%s=> ",&temp->IPArray[j]);
    temp = temp->ptr;
j++;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.