Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct thing {
- unsigned int a;
- int b;
- };
- void do_2(struct thing);
- void do_3(struct thing*);
- void do_4(struct thing*);
- void do_5(struct thing*);
- void do_2(struct thing t){
- printf( "do_2(): t.a: %u. Good.\n"
- " setting t.a to 17\n\n", t.a);
- t.a = 17;
- }
- void do_3(struct thing *t){
- printf( "do_3(): t->a: %u. Good.\n"
- " setting t->a to 17\n\n", t->a);
- t->a = 17;
- }
- void do_4(struct thing *t){
- printf( "do_4(): t->a: %u. Good.\n"
- " outsourcing complex operation to do_5()\n\n", t->a);
- do_5(&t); // this is wrong. the t in this function is _already_ a pointer. The result of this error is quite interesting.
- 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);
- do_5(t); // This is the proper way to do it...
- printf("do_4(): Alright! Here you go, main!\n\n");
- }
- void do_5(struct thing *t){
- printf("do_5(): t->a: %u. ", t->a);
- printf("Wow, do_4! That is a large number. Okay... I'm going to increment it.\n\n");
- t->a ++;
- }
- int main(){
- struct thing t = {5,4};
- printf("main(): t.a: %u. Good.\n\n", t.a);
- do_2(t);
- printf("main(): t.a: %u. No good. I wanted it to change *t.a*, not a copy of t.a.\n\n", t.a);
- do_3(&t);
- printf("main(): t.a: %u. Good.\n\n", t.a);
- do_4(&t);
- printf("main(): t.a: %u. What th--? do_4, you're fired!\n", t.a); // ...however, the damage has already been done.
- printf("-- Ya shot yourself in the foot. --\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement