Advertisement
KeithS

C pointer clarification

Apr 21st, 2012
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. /*
  2. WK Shearer, April 2012. This is a revision of pointers in C. Being largely a C++ guy myself,
  3. I ran into some confusion with pointer handling in C, which does not use dereferencing like C++.
  4. Here it is for clarificaction, in a pure C file.
  5. */
  6. #include <stdio.h>
  7.  
  8. struct test
  9. {
  10.     int i_snum;
  11. };
  12.  
  13. void func_1(int*);
  14. void func_2(int*);
  15. void func_3(struct test*);
  16. void func_4(struct test**);
  17. //void func_5(int&);
  18.  
  19. void func_1(int *ptr)
  20. {
  21.     *ptr += 10;
  22.     printf("i_num is %d\n", *ptr);
  23.     func_2(ptr);
  24. }
  25.  
  26. void func_2(int *ptr1)
  27. {
  28.     *ptr1 += 10;
  29. }
  30.  
  31. void func_3(struct test *p_struct)
  32. {
  33.     p_struct->i_snum += 10;
  34. }
  35.  
  36. void func_4(struct test **p_struct)
  37. {
  38.     (*p_struct)->i_snum += 100;
  39.     printf("struct_test.i_snum = %d\n", (*p_struct)->i_snum);
  40.     (**p_struct).i_snum += 50;
  41. }
  42.  
  43. // This is the C++ style that DOES NOT work.
  44. /*
  45. void func_5(int &num)
  46. {
  47.         num += 1;
  48. }
  49. */
  50.  
  51. int main()
  52. {
  53.     int i_num;
  54.     int *p_num;
  55.  
  56.     p_num = &i_num;
  57.  
  58.     *p_num = 14;
  59.  
  60.     printf("i_num is %d\n", i_num);
  61.     func_1(p_num);
  62.     printf("i_num is %d\n", i_num);
  63.     func_1(&i_num);
  64.     printf("i_num is %d\n", i_num);
  65. //    func_5(i_num);
  66. //    printf("i_num is %d\n", i_num);
  67.  
  68.     struct test struct_test;
  69.     struct test *p_test;
  70.  
  71.     p_test = &struct_test;
  72.  
  73.     p_test->i_snum = 100;
  74.     printf("struct_test.i_snum = %d\n", struct_test.i_snum);
  75.  
  76.     func_3(p_test);
  77.     printf("struct_test.i_snum = %d\n", struct_test.i_snum);
  78.  
  79.     func_3(&struct_test);
  80.     printf("struct_test.i_snum = %d\n", struct_test.i_snum);
  81.  
  82.     func_4(&p_test);
  83.     printf("struct_test.i_snum = %d\n", struct_test.i_snum);
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement