// type varname[size] = {init_value_0, init_value_1, ...};
int a[1000] = {1, 2, 3};
// 'a' is the pointer of the 1st index
*a == a[0];
a == &a[0];
// Index pointer location calculation (automatically adjusts for size)
a[i] == *(a + i);
// Allocate a dynamic pointer
int *ptr = malloc(sizeof(int));
float *array = malloc(n * sizeof(float));
// Free memory address (does not change memory value)
free(ptr);
// Returning a pointer
int *test() {
return malloc(3 * sizeof(int));
}
// Returning a pointer with argument
void test(int **ptr_ptr) {
*ptr_ptr = malloc(3 * sizeof(int));
}
// 2D arrays / structs
int **ptrs = malloc(sizeof(int*) * 2);
ptrs[0] = malloc(sizeof(int));
ptrs[1] = malloc(sizeof(int) * 3);
// IMPORTANT: Free 2D structs from bottom up
free(ptrs[1]);
free(ptrs[0]);
free(prts);
Null Termination: C strings are terminated by a NUL \\0
character.
// Define string constant (cannot be changed)
char *str = "Hello"; // [H, e, l, l, o, \\0]
// Define string array
char str1[] = "Hello"; // [H, e, l, l, o, \\0]
// Wrong: Didn't leave space for the NUL termination
char str2[5] = "Hello"; // [H, e, l, l, o]
char str3[11] = "Hello"; // [H, e, l, l, o, \\0, \\0, \\0, \\0, \\0, \\0]
// String length (calculated wrt \\0)
strlen(str3) == 5;
// Copy strings: Make sure to use strncpy and add a null terminator at the end
// sizeof(str1) == 6
strncpy(str1, str3, 6); // strncpy(dest, src, len)
str1[5] = '\\0';
// Append strings (automatically add \\0)
// strncat(dest, src, n new chars not including \\0)
strncat(str3, str1, sizeof(str3) - strlen(str3) - 1);
// str3 = [H, e, l, l, o, H, e, l, l, o, \\0]
// Search for char pointer in string (NULL if not found)
char *p = strchr(str1, 'e');
int index = p - str1;
// Search for substring in string
char *p1 = strstr(str1, "ello");
// String to int
char *leftover;
int v = strtol(str, &leftover, 10);
// Arguments (argc: Number of arguments, argv: Each argument)
// argv[0] is always the path to the program
int main(int argc, char *argv[])
// Define structs
struct Student {
char name[20];
int year;
float gpa;
};
// Instanciate structs
struct Student azalea;
strcpy(azalea.name, "Azalea");
azalea.year = 2;
azalea.gpa = 3.5;
struct Student azalea = {.name = "Azalea", .year = 2, .gpa = 3.5};
// Functions (structs would be copied)
void no_edit(struct Student s) {
s.gpa = 4.0;
}
void edit(struct Student *s) {
(*s).gpa = 4.0;
s->gpa = 4.0;
}
// Define linked list node
typedef struct Node {
int value;
struct Node *next; // NULL when there is no next element
} Node;
// Traverse linked list
Node *lst;
while (lst != NULL) {
// do something with lst->value
lst = lst->next;
}