Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Apr 29th, 2012  |  syntax: None  |  size: 0.61 KB  |  views: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Array length counting anomaly
  2. #include <stdio.h>
  3. int len(int[]);
  4.  
  5. int main (int argc, const char * argv[])
  6. {
  7.     int a[]={1,2,3,4,5,6,7,8};
  8.     int* i = a;
  9.     printf("length is %d",(len(i)));
  10.     return 0;
  11. }
  12.  
  13. int len(int* a){
  14.     int count = 0;
  15.     for (; *a!=''; a++) {
  16.         count++;
  17.     }
  18.     return count;
  19. }
  20.        
  21. size_t length = sizeof(a) / sizeof(a[0]);
  22.        
  23. int a[] = {1,2,3,4,5,6,7,8};
  24. size_t length = sizeof(a) / sizeof(a[0]);
  25.  
  26. // In this case, sizeof(a[0])
  27. // is the same as sizeof(int), because it's an int array.
  28.        
  29. int *a = malloc(sizeof(int) * 10);
  30. size_t length = sizeof(a) / sizeof(a[0]); // WRONG!