Paulo H
Paulo H

Reputation: 77

Linked List with a pointer to a array of char

I have a linked list whose elements are of type

typedef struct List * News;
struct List
    {
         char * Text;
         News NextN;
    };

In the main function I declared an array of type News as follows

News PTH[50];
for (i = 0; i < 50; i++)
    {
         PTH[i] = (News) malloc(sizeof(struct List));
         PTH[i] -> Text = NULL;
         PTH[i] -> NextN = NULL;
    }

I added new nodes in the beginning of the list with

if ( PTH[i] -> Text == NULL)
    PTH[i] -> Text = msg;
else 
    {
        t -> Text = msg;
        t -> NextN = PTH[i];
        PTH[i] = t;
    }

Where msg is a array of char of length 2000; and and then tried to print the texts apointed by PTH[i] -> Text with

p = PTH[i];
if (p -> Text != NULL)
    {
        printf("%s", p -> Text);
        p = p -> NextN;
    }
while (p != NULL)
    {
        printf("%s", p -> Text);
        p = p -> NextN;
    }
}

This algorithm only add one node. The error is how I define the PTH or is there an error in how I put nodes in the list.

Upvotes: 0

Views: 3947

Answers (2)

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

Assuming that msg is a buffer you use to receive new data, you have to be careful with this statement:

PTH[i] -> Text = msg;

Since msg is a pointer to char, the assignment will not copy the characters sequence; instead, it will just make PTH[i]->Text point to the same location as msg. This is problematic if you change the contents in msg - the changes are, of course, reflected back in every PTH[i]->Text for which the assignment was made, namely, every node that you ever added. Probably, not quite what you want. This is why it seems like you can only handle one node at a time. They all get the same text, because they all point to the same memory location.

You should use strcpy instead:

strcpy(PTH[i]->Text, msg);

Don't forget to include string.h.

This assumes that PTH[i]->Text is already allocated. You might want to use strncpy if there is a chance that msg exceeds 2000 characters, to avoid buffer overflows.

If you didn't alloc space for PTH[i]->Text, you could allocate exactly strlen(msg)+1 positions for PTH[i]->Text and then use strcpy safely. Or you could use strdup, also declared in string.h, which has exactly this behavior:

PTH[i]->Text = strdup(msg);

Upvotes: 1

AndersK
AndersK

Reputation: 36082

maybe it is something like this you are after:

if ( PTH[i]->Text == NULL )
{
  PTH[i]->Text = msg;
}
else // first create node, then append by first finding the last node
{
  News it = NULL;
  News t = malloc( sizeof(struct List));
  t->Text = msg;
  t->NextN = NULL;

  for ( it = PTH[i]->NextN; it != NULL; it = it->NextN)
  {
    ;
  }
  it->NextN = t;
}

Upvotes: 2

Related Questions