Skip to content

Instantly share code, notes, and snippets.

@timdrichards
Last active March 30, 2022 16:23
Show Gist options
  • Save timdrichards/87243880d52ba7722f8a4b8bddeec0a6 to your computer and use it in GitHub Desktop.
Save timdrichards/87243880d52ba7722f8a4b8bddeec0a6 to your computer and use it in GitHub Desktop.
C pointers, arithmetic, & types
#include <stdio.h>
#include <stdlib.h>
int main() {
char* c = malloc(10);
int* i = malloc(10);
// Print the size of a char and int type.
printf("Size of char is %lu.\n", sizeof(char));
printf("Size of int is %lu.\n", sizeof(int));
// Print the address of c and i.
printf("Address of c is %p.\n", c);
printf("Address of i is %p.\n", i);
// Print the address of c+1 and i+1.
printf("Address of c+1 is %p.\n", c+1);
printf("Address of i+1 is %p.\n", i+1);
// Convert the addresses to long in order to show the difference.
// Note: if you don't do this, the difference will be 1 since the
// compiler will take the type under consideration.
long pc_value = (long) c;
long pc_value_inc = (long) (c + 1);
long pi_value = (long) i;
long pi_value_inc = (long) (i + 1);
// Print the difference between the addresses.
printf("The c pointer is incremented by %ld.\n", pc_value_inc - pc_value);
printf("The i pointer is incremented by %ld.\n", pi_value_inc - pi_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment