Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a parameter is a pointer type, is the parameter a pointer allocated in local memory

Tags:

c

pointers

struct

I'm just learning C, and I have a question about pointer parameters. My code is the following:

int Length(node *head)
{
  int length = 0;

  while (head) {
    length++;
    head = head->next;
  }

  return length;
}

The code in the book I'm reading says to do this though:

int Length(struct node* head)
{
    struct node* current = head;
    int count = 0;

    while (current != NULL) {
        count++;
        current = current->next;
    }

    return count;
}

Is there really a difference? The way I'm reading my code is that I get a pointer to a node struct as a parameter. The pointer itself however, is a local variable that I am free to mutate as long as I don't dereference it first. Therefore, I can change the value of the pointer to point to a different node (the next node as it may be).

Will this cause a memory leak or is there some other difference I'm not seeing?

This code is for a linked list implementation. The node struct is defined as:

// Define our linked list node type
typedef struct node {
  int data;
  struct node *next;
} node;
like image 568
Brandon Wamboldt Avatar asked May 08 '26 04:05

Brandon Wamboldt


1 Answers

Yes, they are both doing the same. But in the second example, it is more clear what the author is trying to do because of the code. In your first example, you're using the pointer head to reference nodes other than the head. That can be confusing.

You could write your function like this and your intend would be clear:

int GetLength(node* current)
{
  int length = 0;

  while (current != NULL)
  {
    length += 1;
    current = current->next;
  }

  return length;
}
like image 79
Marcos Avatar answered May 09 '26 23:05

Marcos