code_junkie

right usage of pointer to pointer

Nov 13th, 2011
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. void func(ABC ** ptr); //func is provided by someone else and i don't know about the implementation.
  2. {
  3.  
  4.  
  5. }
  6.  
  7. ABC xyz[2];
  8. ABC * ptr = xyz;
  9.  
  10. ABC **dptr1 = &ptr; //pointer to ponter
  11.  
  12. ABC ** dptr2 = (ABC **)malloc(2*sizeof(struct abc*)); //pointer to arrary of pointers
  13.  
  14. dptr2[0] = &xyz[0];
  15. dptr2[1] = &xyz[1];
  16.  
  17. ABC xyz[2]; // two ABC's
  18. ABC * ptrs[2]; // array of pointers to ABC's
  19. ptrs[0] = &xyz[0];
  20. ptrs[1] = &xyz[1];
  21. func(ptrs); // C compiler convers an array of pointers to
  22. // a pointer to pointers when passing it to a function
  23.  
  24. void func(ABC** ptr)
  25. {
  26. }
  27.  
  28. ABC xyz[2];
  29. ABC* ptr = xyz;
  30.  
  31. ABC** dptr1 = &ptr; //pointer to ponter
  32. // or
  33. ABC* dptr1[] = {xyz}; //pointer to an array.
  34. //Thus making dptr the 'logical' equivalent of ABC[1][2]
  35.  
  36.  
  37. > if i pass dptr1 to func, and func does something like *ptr[0] and *ptr[1] to access the actual values, it fails.
  38.  
  39. ABC value[1][2];
  40.  
  41. ABC row1[3] = {/*STUFF 1*/};
  42. ABC row2[3] = {/*STUFF 2*/};
  43. ABC row3[3] = {/*STUFF 3*/};
  44. ABC* data[3] = {row1,row2,row3}; // logical ABC data[3][3];
  45.  
  46. func(data);
  47.  
  48. #define count(ARRAY) (sizeof(ARRAY)/sizeof(*ARRAY))
  49.  
  50. void func(struct ABC * array, size_t elementCount) {...}
  51.  
  52. struct ABC anArray[2] = {...};
  53. func(anArray, count(anArray));
  54.  
  55. struct ABC array[2] = {...};
  56. struct ABC * parray[count(array)];
  57.  
  58. for(size_t i = 0; i < count(array); ++i)
  59. parray[i] = &array[i];
  60.  
  61. struct ABC * parray[count(array) + 1];
  62. parray[count(array)] = NULL;
  63.  
  64. struct ABC parray[][1] = {
  65. { {/* first struct's initializer */} },
  66. { {/* second struct's initializer */} },
  67. { {/* third struct's initializer */} }
  68. };
  69.  
  70. func(parray, count(parray));
  71.  
  72. struct ABC
  73. {
  74. // some members;
  75. };
  76.  
  77.  
  78. void func( ABC* firstElemOfArray, int countOfElementsInArray)
  79. {
  80. for( int i = 0; i < countOfElementsInArray; ++i )
  81. {
  82. ABC* currentElement = firstElemOfArray + i;
  83. // do something with current elements
  84. }
  85. }
  86.  
  87. void useFunc()
  88. {
  89. ABC array[2] = { new ABC(), new ABC() };
  90.  
  91. func( array, sizeof(array/sizeof(array[0]) );
  92. }
  93.  
  94. typedef ABC* ABC_ptr;
  95.  
  96. ABC_ptr *dptr2 = new ABC_ptr[2];
Add Comment
Please, Sign In to add comment