code_junkie

How can I get the size of an array from a pointer in C?

Nov 11th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {
  2. /* handle error */
  3. }
  4.  
  5. int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)
  6.  
  7. void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));
  8. *((unsigned long int*)p) = n;
  9.  
  10. void *arr = p+sizeof(unsigned long int);
  11.  
  12. typedef struct {
  13. unsined int n;
  14. void *arr;
  15. } arrInfo;
  16.  
  17. typedef void* arrayInfo;
  18. (arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);
  19. (void)deleteArrayInfo(arrayInfo);
  20. (unsigned int)arrayLength(arrayInfo);
  21. (void*)arrayPtr(arrayInfo);
  22. ...
  23.  
  24. void *blockOfMem = malloc(sizeof(mystruct)*n + sizeof(int));
  25.  
  26. ((int *)blockofMem)[0] = n;
  27. mystruct *structs = (mystruct *)(((int *)blockOfMem) + 1);
  28.  
  29. typedef struct MyStructTag
  30. { /* etc. */ } MyStruct ;
  31.  
  32. void doSomething(MyStruct * p)
  33. {
  34. /* well... extract the memory allocated? */
  35. size_t i = get_size(p) ;
  36. initializeMyStructArray(p, i) ;
  37. }
  38.  
  39. void doSomethingElse()
  40. {
  41. MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */
  42. doSomething(s) ;
  43. }
  44.  
  45. void doSomethingElse()
  46. {
  47. MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */
  48. MyStruct * s2 = s + 5 ; /* s2 points to the 5th item */
  49. doSomething(s2) ; /* Oops */
  50. }
  51.  
  52. int size;
  53. struct mystruct *cur;
  54.  
  55. for (cur = myarray; cur->name != NULL; cur++)
  56. ;
  57.  
  58. size = cur - myarray;
  59.  
  60. void* my_malloc(size_t s); /* Calls malloc(s), and if successful stores
  61. (p,s) in a list of handled blocks */
  62. void my_free(void* p); /* Removes list entry and calls free(p) */
  63. size_t my_block_size(void* p); /* Looks up p, and returns the stored size */
  64. ...
  65.  
  66. #include <stdio.h>
  67.  
  68. float a, b, c, d, e, f, g;
  69.  
  70. float myMax(float *apa,int soa){
  71. int i;
  72. float max = apa[0];
  73. for(i=0; i< soa; i++){
  74. if (apa[i]>max){max=apa[i];}
  75. printf("on i=%d val is %0.2f max is %0.2f, soa=%dn",i,apa[i],max,soa);
  76. }
  77. return max;
  78. }
  79.  
  80. int main(void)
  81. {
  82. a = 2.0;
  83. b = 1.0;
  84. c = 4.0;
  85. d = 3.0;
  86. e = 7.0;
  87. f = 9.0;
  88. g = 5.0;
  89. float arr[] = {a,b,c,d,e,f,g};
  90.  
  91. float mmax = myMax((float *)&arr,(int) sizeof(arr)/sizeof(arr[0]));
  92. printf("mmax = %0.2fn",mmax);
  93.  
  94. return 0;
  95. }
Add Comment
Please, Sign In to add comment