1 year ago

#366098

test-img

cfrost6

C: char array data being overwritten

I am trying to write code to output a list (homework assignment for learning linkedLists). I have code for adding an element to a linkedList, at the end, and managing the pointers:

void addEnd( LinkedList *someList, void *newData )
{
  Node *newNode = malloc ( sizeof ( Node ) );

  newNode->data = newData;          // set the fields of the new Node
  newNode->next = someList->header;
  newNode->prev = someList->header->prev;

  someList->header->prev->next = newNode;  // splice-in the newNode
  someList->header->prev = newNode;        // into the List

  someList->size++;
}

Where i'm running into some issues is with stdin and getting it to output properly.

char currChar = getchar();
   while(currChar != EOF)
   {
      if (currChar == 'a')
      {
          currChar = getchar();//Skip over space
          if (currChar == SPACE)
          {
              //Get the name to add to list (must be less than 20 characters)
              currChar = getchar();
              char name[MAX_NAME_LENGTH] = {0};
              int count = 0;
              while (count<MAX_NAME_LENGTH && currChar != NEWLINE)
              {
                  name[count] = currChar;
                  currChar = getchar();
                  count++;
              }
              currChar = getchar();
              addEnd(roster, name);
              outputList(roster);
          }
          else // If no space after 'a' then exit
          exit(1);
       }
       else
          exit(1);
   }

Output:

[alice]
[bob bob]
[chad chad chad]
[dan dan dan dan]

Im fairly certain the issue is with: "char name[MAX_NAME_LENGTH] = {0};"

Since, if i'm understanding correctly, this is using the same char array for each name. Just unsure of how to avoid this. Is there a way to use pointers to achieve what I want here?

c

pointers

char

stdin

dereference

0 Answers

Your Answer

Accepted video resources