Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. # Oh shit C!
  2. Some C examples for quick reference.
  3.  
  4. ## Strings
  5. ```c
  6. // remember the null terminator!
  7. char greet[] = {'H', 'e', 'l', 'l', 'o', '\0'};
  8.  
  9. int len = sizeof(greet) / sizeof(char);
  10. for (i = 0; i < len; i++) {
  11. printf("%c", greet[i]);
  12. }
  13. ```
  14.  
  15. ## Arrays
  16. ```c
  17. // pointer to array of names
  18. char *names[] = {
  19. "Foobar", "BarBaz"
  20. };
  21. ```
  22.  
  23. ## Pointers
  24.  
  25. ### Address/Reference operator
  26. ```c
  27. int age = 35;
  28. int *age_ptr = &age;
  29. ```
  30. ### Dereferencing
  31. ```c
  32. int age = 35;
  33. int *age_ptr = &age;
  34.  
  35. // deference example
  36. assert(++*age_ptr == 36)
  37. ```
  38. ### Pointer to Pointer
  39. ```c
  40. int age = 35;
  41. int *age_ptr = &age;
  42. int **age_ptr_ptr = &age_ptr;
  43. // and so on
  44.  
  45. // needs to include <assert.h>
  46. assert(**age_ptr_ptr, *age_ptr);
  47. ```
  48.  
  49. ### Pointer to Array
  50. ```c
  51. int ages[3] = {10, 20, 30};
  52. int *ages_ptr = ages;
  53.  
  54. for (int i = 0; i < 3; i++) {
  55. assert(*(ages_ptr + i) == ages[i]);
  56. }
  57. ```
  58. ### Pointer to Function
  59. ```c
  60. int add(int a, int b)
  61. {
  62. return a + b;
  63. }
  64.  
  65. int (*plus)(int, int);
  66. plus = add;
  67.  
  68. assert(plus(2, 2) == add(2, 2));
  69. ```
  70.  
  71. ### Pointer to Structures
  72. ```c
  73. struct Point
  74. {
  75. int x;
  76. int y;
  77. };
  78.  
  79. // need to include <stdlib.h> for malloc
  80. struct Point *point = malloc(sizeof(struct Point));
  81. point->x = 5;
  82. point->y = 5;
  83.  
  84. assert(point->x == 5);
  85. assert(point->y == 5);
  86.  
  87. // make sure to free it up!
  88. free(point);
  89. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement