Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Oh shit C!
- Some C examples for quick reference.
- ## Strings
- ```c
- // remember the null terminator!
- char greet[] = {'H', 'e', 'l', 'l', 'o', '\0'};
- int len = sizeof(greet) / sizeof(char);
- for (i = 0; i < len; i++) {
- printf("%c", greet[i]);
- }
- ```
- ## Arrays
- ```c
- // pointer to array of names
- char *names[] = {
- "Foobar", "BarBaz"
- };
- ```
- ## Pointers
- ### Address/Reference operator
- ```c
- int age = 35;
- int *age_ptr = &age;
- ```
- ### Dereferencing
- ```c
- int age = 35;
- int *age_ptr = &age;
- // deference example
- assert(++*age_ptr == 36)
- ```
- ### Pointer to Pointer
- ```c
- int age = 35;
- int *age_ptr = &age;
- int **age_ptr_ptr = &age_ptr;
- // and so on
- // needs to include <assert.h>
- assert(**age_ptr_ptr, *age_ptr);
- ```
- ### Pointer to Array
- ```c
- int ages[3] = {10, 20, 30};
- int *ages_ptr = ages;
- for (int i = 0; i < 3; i++) {
- assert(*(ages_ptr + i) == ages[i]);
- }
- ```
- ### Pointer to Function
- ```c
- int add(int a, int b)
- {
- return a + b;
- }
- int (*plus)(int, int);
- plus = add;
- assert(plus(2, 2) == add(2, 2));
- ```
- ### Pointer to Structures
- ```c
- struct Point
- {
- int x;
- int y;
- };
- // need to include <stdlib.h> for malloc
- struct Point *point = malloc(sizeof(struct Point));
- point->x = 5;
- point->y = 5;
- assert(point->x == 5);
- assert(point->y == 5);
- // make sure to free it up!
- free(point);
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement