user12239061
user12239061

Reputation:

Declaring pointer to NULL

When I declare:

struct str_node{
    int data;
    struct str_node *next;
}node;

node *head = NULL;

Is it something like:

head = NULL;

or

*head = NULL

Upvotes: 1

Views: 158

Answers (4)

ssd
ssd

Reputation: 2432

Define a pointer and set its value to NULL:

int *head = NULL;
// conceptual    memory address    value
// head          0xABCD0000        0          
// that is;
// head is pointing to nowhere

Define a pointer then set its value to NULL:

int *head;
head = NULL;
// conceptual    memory address    value
// head          0xABCD0000        0          
// that is;
// head is pointing to nowhere

Define a pointer then set the memory address it's pointing at to 0:

int *head;
head = 0xDCBA0000; // or a "malloc" function 
*head = 0;
// conceptual    memory address    value
// head          0xABCD0000        0xDCBA0000          
// ...
// *head         0xDCBA0000        0
// that is;
// head is pointing to 0xDCBA0000
// and the value of the memory it's pointing at is set to zero

Upvotes: 2

Roberto Caboni
Roberto Caboni

Reputation: 7490

Every declaration is in the following format:

Type varName = initializer;

In your case

node *     head          =   NULL;
 ^          ^                 ^
| Type |  | varName | = | initializer |;

So, head is a variable which type is node * (pointer to node). The variable is head which value is initialized to NULL.

Upvotes: 7

sebastian
sebastian

Reputation: 412

I would like to expand Roberto's answer.

This

node *head = NULL;

will NOT compile because node is not a type, it's actually a variable struct str_node named node. If you want to define a type, use the typedef specifier, like so

typedef struct str_node{
    int data;
    struct str_node *next;
}node;

node *head = NULL;

Upvotes: 5

zgyarmati
zgyarmati

Reputation: 1153

Welcome to SO! It's like head = NULL;

Upvotes: 0

Related Questions