0

I am observing that only part of an fixed size array is passed to the argument of the function. The argument of the function is a dynamic array. Please look at the observation given below and help in pointing out the issue.

Code

void check_errors(int val, int fault_nums[]) {
    PRINT("size of array=%d\nsize of first element of an array=%d",sizeof(fault_nums),sizeof(fault_nums[0]));
    ...
}

main(){
    int farry[6] = {82,83,84,85,199,229};
    PRINT("TEST:size of array=%d\nTEST:size of first element of an array=%d",sizeof(farry),sizeof(farry[0]));  //PRINT is a predefined function
    check_errors(1, farry);
    ...
}

Observation

PRINT: TEST:size of array=24 TEST:size of first element of an array=4

PRINT: size of array=8 size of first element of an array=4

ysaini
  • 1
  • When you pass an array to a function you are actually passing a pointer to the base address of the array, when you write sizeof(fault_nums) it is the size of the pointer to the array not the number of elements in the array, to get the number of elements you need to replace with sizeof(fault_nums) / sizeof(fault_nums[0]), however I don't think that will work in a function as sizeof(fault_nums) will be the size of the pointer, not the array. – SPlatten Nov 09 '17 at 07:20
  • Thanks for the response. Used the solution provide in https://stackoverflow.com/questions/4772752/problem-with-sizeof-operator – ysaini Nov 09 '17 at 15:22
  • your choice, however I prefer to use the size of the actual array element itself instead of naming a type. – SPlatten Nov 10 '17 at 16:07

1 Answers1

0

To correctly identify the size of an array:

void main() {
    int farry[6] = {82,83,84,85,199,229};
    size_t szSingleElement = sizeof(farry[0])
          ,szNumOfElements = sizeof(farry) /szSingleElement;
    printf("TEST:size of array=%u\nTEST:size of first element of an array=%u",szNumOfElements,szSingleElement));  //PRINT is a predefined function
}

On a 32bit system an integer will be 4 bytes and a pointer will also be 4 bytes.

SPlatten
  • 5,334
  • 11
  • 57
  • 128