1

I've got a LinkedList node struct defined as such:

struct intnode {
    int item;
    struct intnode *next;
};
typedef struct intnode IntNode;

Which I am using to do some simple sorting. However, in creating this linked list, I am having difficulty with scope. In my main function I've got a Null header IntNode object to serve as the first element in the list, however I can't modify it within my insert function, despite the fact that I'm passing a pointer to it. The code never reaches the print statement saying the list is no longer empty, which I am confused by. Does this have something to do with defining a new IntNode element to add within the insert function which is then thrown away after the function is done?

int main() {

  IntNode *header = NULL;

  printf("Enter some numbers, ending with -1: ");
  int a;

  while(a != -1) {
    scanf("%d",&a);
    if(a != -1) {
      insert(header, a);
    }
  }
  return 0;
}

IntNode *createNode(int val) {
  IntNode *new_node;
  new_node = malloc(sizeof(IntNode));
  new_node->item = val;
  return new_node;
}

void insert(IntNode *header, int val) {

  IntNode *newNode = createNode(val);

  if(header == NULL) { //list is empty, so insert at front
    printf("list still empty\n");
    newNode->next = header;
    header = newNode;
    printf("%d",header->item);
  } else {
    printf("the list is no longer empty...");
    //do more stuff here
    }
}
jwise
  • 11
  • 1
  • Additionally, I am unable to change arguments for insert – jwise May 01 '20 at 01:09
  • 1
    Does this answer your question? [Changing address contained by pointer using function](https://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function) – kaylum May 01 '20 at 01:14
  • Add it on the end, not the start. – tadman May 01 '20 at 01:14

1 Answers1

0

If you want to modify a pointer, you need to pass a pointer of that pointer. Therefore

insert(header, a);

should be

insert (&header, a);

and adjust your insert() function accordingly.

user12986714
  • 741
  • 2
  • 8
  • 19