Skip to content

Instantly share code, notes, and snippets.

@nkcr
Last active August 29, 2015 14:12
Show Gist options
  • Save nkcr/403c4fdd9b0c1968c51c to your computer and use it in GitHub Desktop.
Save nkcr/403c4fdd9b0c1968c51c to your computer and use it in GitHub Desktop.
lonely C
//
// A pointer is ...
uint16_t * pointer; // will point on a 16 integer bit data (sizeof = 2 bytes)
//
//
// Write at reg @
//
volatile uint16_t * reg = (volatile uint16_t *) 1234; // 1234 is the @
*reg = 4321; // 4321 is the new value
//
// Read at reg @
//
volatile uint16_t * reg = (volatile uint16_t *) 1234; // 1234 is the @
uint16_t result = *reg;
//
// Get reg @ of a variable
//
char a = 'a';
char * reg;
reg = &a // char * reg = &a;
//
// Reference a struct
//
struct animal pony;
struct animal * reg = &pony;
(*reg).tail = ... ; reg->tail = ... ; pony.tail = ... ;
(*reg).speed = ... ; reg->speed = ... ; pony.speed = ... ;
//
// iterate trough array
//
uint8_t array[3];
uint8_t * reg;
reg = array;
reg[2] = ... ; // it is possible, indeed
for(int i=0; i<5; i++) {
*tab++ = ... ; // incrementation is made accordingly (1 byte here)
}
//
// Pointer arithmetic (think of bytes)
//
char * reg = (char*)100; reg++; // reg = 101
uint32_t * reg = (uint32_t*)100; reg++ // reg = 104
//
// Dynamic pointers
// use malloc, calloc, and free from stdlib.
// Malloc means memory allocation, calloc behaves like malloc but initialize to 0
//
struct animal * pony = malloc(sizeof(struct animal));
free(pony); // pony = NULL or 0
//
// Function pointer
//
int say_hello(char param) {
// ...
}
int(*reg)(char);
reg = say_hello; // reg = &say_hello;
int result = reg('a'); // int result = (*reg)('a');
// array
int(*reg[10])(..., ...);
reg[1] = say_hello(..., ...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment