欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Notes on Pointers and LinkedList in C

程序员文章站 2022-03-01 17:21:20
...

Notes on Pointers and LinkedList in C

Three important things to know about pointers in C

1. What is pointer in C

A pointer is a variable that stores the address of another variable.

2. Two ways to access a pointer

Direct Access by variable name;
Indirect Access by address.

3. Mind the Memory Locate (IMPORTANT)

Unlike
int a[10]; which allocated 10 * 4 bytes in memory,
int *p; only allocated 8 bytes in memory to store the address of another variable.

A pointer that’s not been initialized is called a “wild pointer”, which address stored is a random one;
A pointer point to 0x0 or NULL is a “null pointer”.

Do NOT access a wild pointer or a null pointer. This will cause  Segmentation fault (core dumped)  error.

Pointers and Struct

When using pointer to point to a struct, it must ne initialized. i.e.

struct *Foo f = (struct Foo*)malloc(sizeof(struct Foo));

And to access members in the struct, -> must be used instead of . i.e.

struct Foo f1;
struct *Foo f2 = (struct Foo*)malloc(sizeof(struct Foo));

int a = f1.num;
int b = f2->num;

LinkedList Using Struct Pointers

Initialize Nodes Using for Loop

// initialize head
struct Node *head = (Node *)malloc(sizeof(Node));
head->data = 0;
head->next = NULL;

// set tail to head
struct Node *tail = head;

// initalize the rest of nodes
for (int i = 0; i < size - 1; i++)
{
    // initalize a new node
    struct Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = 0;
    
    // set newNode to be the next node and tail of the list
    tail->next = newNode;
    tail = tail->next;
    
    // set the tail's next to NULL
    tail->next = NULL;
}