Question on passing a pointer to a structure in C to a function?

Posted by worlds-apart89 on Stack Overflow See other posts from Stack Overflow or by worlds-apart89
Published on 2010-04-15T21:01:53Z Indexed on 2010/04/15 21:03 UTC
Read the original article Hit count: 193

Filed under:
|
|
|

Below, I wrote a primitive singly linked list in C. Function "addEditNode" MUST receive a pointer by value, which, I am guessing, means we can edit the data of the pointer but can not point it to something else. If I allocate memory using malloc in "addEditNode", when the function returns, can I see the contents of first->next ? Second question is do I have to free first->next or is it only first that I should free? I am running into segmentation faults on Linux.

#include <stdio.h>
#include <stdlib.h>

typedef struct list_node list_node_t;

struct list_node
{ 
  int value;
  list_node_t *next;
};

void addEditNode(list_node_t *node)
{
   node->value = 10;
   node->next =  (list_node_t*) malloc(sizeof(list_node_t));
   node->next->value = 1;
   node->next->next = NULL; 
}

int main()
{
  list_node_t *first = (list_node_t*) malloc(sizeof(list_node_t));

  first->value = 1;
  first->next = NULL;

  addEditNode(first);

  free(first);

  return 0;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about structure