2
#define lengthOfArray(x)  (sizeof(x) / sizeof(x[0]))

seems to give the right answer in main(), but in the printf() of array_set(). Did I miss something?

int* decValue2[BUF_SIZE] = {
  0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 
  0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
};

#define lengthOfArray(x)  (sizeof(x) / sizeof(x[0]))


void array_set(int* y_dest, int* y_src, int arrayLength){ // arrays
     int i = 0;

     printf("lengthOfArray in function: %d \n", lengthOfArray(y_src));  
     // [TODO] check that y_dest has enough space
     for (i=0;i<arrayLength; i++)
         y_dest[i] = y_src[i];
    // 
}


// In main()

    int y_int = 0;
    int y_array[BUF_SIZE];

    int_set_right( &y_int, 9876543);
    array_set(y_array, decValue2, BUF_SIZE);

    printf("lengthOfArray: %d \n", lengthOfArray(y_array));  

    printf("Value int :: %d \n",y_int);
         int i = 0;
     for (i=0;i<BUF_SIZE; i++) 
         printf("%x ", (0xff & y_array[i]));    
devnull
  • 118,548
  • 33
  • 236
  • 227
Ursa Major
  • 851
  • 7
  • 25
  • 47
  • 2
    Possible duplicate of [c, finding length of array inside a function](http://stackoverflow.com/questions/17590226/c-finding-length-of-array-inside-a-function). There are probably other duplicates for this question — this was in the 'related' list. In fact, here's a 7-digit (older) question: [Sizeof an array in the C programming language](http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language). – Jonathan Leffler Oct 02 '13 at 15:06

2 Answers2

4

lengthOfArray won't work correctly for pointers (as opposed to arrays), since sizeof(x) will return the size of the pointer and not the size of the pointed-to array.

You have to explicitly pass the size of the array into the function (as you already do).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You cannot get the length of an array with only a pointer to it. It's generally not a good idea to use pointers and arrays together, instead you should use vectors which tend to be much easier to work with.

The lengthOfArray(x) gives you the right value in main because it's just the array, not a pointer to the array. You could get the length here, and pass it in anywhere you need it.