c syntax

This article records my C learning notes, keeps developing…

Chinese Version: 这篇文章记录我对C语言的学习心得和基本使用方法,以便以后手生的时候快速上手。

Pointer

If you want to store value in memory via pointer, then you have to ensure the pointer is already allocated memory before you assign any value to it. In following example, you implicitly allocate memory to pointer p_int.

int a = 1;
int *p_int = a;

While, when dealing with data structures (string, array of objects) you keep adding elements from time to time. Always declare it using NULL, and allocate memory before assigning value. Otherwise, Segmentation Fault happens when you try to access a null pointer.

List/Array Traversal

Pointers can be manipulated to do array/list traversal. To reach that, KEEP IN MIND decare a constant variable to store the head pointer.

int size = 10;
int *array = malloc(size*sizeof(int));

// assign the 1st element
array = ...; 

// store pointer to 1st element
constant int *head = array; 

// 2nd element
array++;
array = ...;