-1

I created a header file named functions.h and a source file named test.c. I want to count the size of an array by doing size=sizeof(arr)/arr[0].

If I do it in the main function, the expression works. However, it does not when I apply the header file.

For header file: functions.h

#ifndef C2A1E1_MACROS_H_INCLUDED
#define C2A1E1_MACROS_H_INCLUDED

double SizeofArray(double a[]) {
    int b = 0;
    b = sizeof(a) / sizeof(a[0]);

    return b;
}
#endif // C2A1E1_MACROS_H_INCLUDED

For source file: test.c

#include <stdio.h>
#include "functions.h"

int main(void) {
    double arr[] = { 1, 2, 3, 4, 5 };
    double arrSize = 0;

    double n1 = sizeof(arr);
    printf("n1= %f\n", n1);
    double n2 = sizeof(arr[0]);
    printf("n2= %f\n", n2);
    double ArrSize = n1 / n2;
    printf("ArrSize= %f\n", ArrSize);

    //Applied Function
    arrSize = SizeofArray(arr);
    printf("Array Size= %f\n", arrSize);

    return 0;
}

This is the result when I run my program with Array Size = 0, but it is supposed to be 5: This

Clifford
  • 88,407
  • 13
  • 85
  • 165

1 Answers1

2

SizeofArray cannot be implemented as a function because the function receives a pointer to the array, from which it cannot compute the length of the array with the posted expression.

You can define a macro for this purpose, but keep in mind that it is quite error prone as even the macro will fail when invoked with a pointer instead of an actual array:

#define SizeofArray(a)  (sizeof(a) / sizeof(*(a)))

This page has somewhat portable methods to try and detect if a is an actual array: Array-size macro that rejects pointers

chqrlie
  • 131,814
  • 10
  • 121
  • 189