Skip to content

Instantly share code, notes, and snippets.

@shaikhul
Last active September 6, 2019 04:54
Show Gist options
  • Save shaikhul/a82186a397a98f26ab170ee3614ac884 to your computer and use it in GitHub Desktop.
Save shaikhul/a82186a397a98f26ab170ee3614ac884 to your computer and use it in GitHub Desktop.
Oh shit C!

Oh shit C!

Some C examples for quick reference.

Strings

// 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

// pointer to array of names
char *names[] = {
  "Foobar", "BarBaz"
};

Pointers

Address/Reference operator

int age = 35;
int *age_ptr = &age;

Dereferencing

int age = 35;
int *age_ptr = &age;

// deference example
assert(++*age_ptr == 36)

Pointer to Pointer

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

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

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

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment