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?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Sumedh Junghare
  • 381
  • 2
  • 4
  • 21
  • `char *IPArray[100];` → `char IPArray[100];`, `scanf("%s",&head->IPArray[i]);` → `scanf("%s", head->IPArray[i]);`, `printf("%d=> ",temp->IPArray);`→ `printf("%s=> ",temp->IPArray);` – Spikatrix Mar 04 '16 at 05:40
  • [don't cast the result of malloc in C](http://stackoverflow.com/q/605845/995714) – phuclv Mar 04 '16 at 05:43
  • Your character array "char *IPArray[100] "is actually an array of character pointers.It stores character addresses. – Anil Kumar Mar 04 '16 at 07:27

2 Answers2

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.

Community
  • 1
  • 1
Vagish
  • 2,520
  • 19
  • 32
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++;

}
Anil Kumar
  • 348
  • 5
  • 16