Advertisement
B1KMusic

How to shoot yourself in the foot with struct pointers

Oct 14th, 2015
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. struct thing {
  4.     unsigned int a;
  5.     int b;
  6. };
  7.  
  8. void do_2(struct thing);
  9. void do_3(struct thing*);
  10. void do_4(struct thing*);
  11. void do_5(struct thing*);
  12.  
  13. void do_2(struct thing t){
  14.     printf( "do_2(): t.a: %u. Good.\n"
  15.             "        setting t.a to 17\n\n", t.a);
  16.     t.a = 17;
  17. }
  18. void do_3(struct thing *t){
  19.     printf( "do_3(): t->a: %u. Good.\n"
  20.             "        setting t->a to 17\n\n", t->a);
  21.     t->a = 17;
  22. }
  23. void do_4(struct thing *t){
  24.     printf( "do_4(): t->a: %u. Good.\n"
  25.             "        outsourcing complex operation to do_5()\n\n", t->a);
  26.     do_5(&t); // this is wrong. the t in this function is _already_ a pointer. The result of this error is quite interesting.
  27.     printf("do_4(): t->a: %u. What the hell!? Hey do_5, that was wrong! W.R.O.N.G. Oh wait...sorry. Let's do it again.\n\n", t->a);
  28.     do_5(t); // This is the proper way to do it...
  29.     printf("do_4(): Alright! Here you go, main!\n\n");
  30. }
  31. void do_5(struct thing *t){
  32.     printf("do_5(): t->a: %u. ", t->a);
  33.     printf("Wow, do_4! That is a large number. Okay... I'm going to increment it.\n\n");
  34.     t->a ++;
  35. }
  36. int main(){
  37.     struct thing t = {5,4};
  38.     printf("main(): t.a: %u. Good.\n\n", t.a);
  39.     do_2(t);
  40.     printf("main(): t.a: %u. No good. I wanted it to change *t.a*, not a copy of t.a.\n\n", t.a);
  41.     do_3(&t);
  42.     printf("main(): t.a: %u. Good.\n\n", t.a);
  43.     do_4(&t);
  44.     printf("main(): t.a: %u. What th--? do_4, you're fired!\n", t.a); // ...however, the damage has already been done.
  45.     printf("-- Ya shot yourself in the foot. --\n");
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement