-3

How to create a function to get the size of an array in C? Function and array aren't from the same scope. for example:

int func(int arr[]);

int main(){
    int arr[5];
}
int arr_length(int arr[]){
    int length = sizeof(arr)/sizeof(int);
    return length;
}

The problem with the function above that it treats arr as a pointer so it has the size of a pointer

8
  • 4
    In arr_length, the arr parameter is a pointer. In C, the way is to pass the length along with the pointer: int arr_length(int arr[], size_t arr_size) { return arr_size; } Commented Jan 4, 2024 at 16:23
  • 3
    The declaration int func(int arr[]); is really the same as int func(int *arr); Commented Jan 4, 2024 at 16:34
  • 2
    @Bathsheba: Are you thinking of something like malloc_usable_size, or other things that are only for dynamically allocated memory. If not, what platform provides a way for func to get the size associated with its arr parameter when the caller defined int a[3][5] and passed a[1]? Commented Jan 4, 2024 at 16:35
  • 1
    @i486, did you mean a size_t parameter? int cannot portably represent all possible sizes. Commented Jan 4, 2024 at 16:42
  • 1
    @EricPostpischil: I intentionally shied away from enumerating any techniques, as they become more and more desperate in solving a problem that's best solved by keeping track of the size in a conventional manner. It can't be done in standard C; that's the point I was attempting to make. Commented Jan 4, 2024 at 17:20

1 Answer 1

1

simply pass the array length along with the pointer to the array in the arguments, this is pretty common

int some_func(int arr[], int n);

Or create a more sophisticated structure for arrays in your application:

typedef struct {
  int *vector;
  int length;
  int capacity;
} Array;

you can also use my implementations: https://gist.github.com/arianito/57e668790b723a6e6649d4535e9dcaae

Sign up to request clarification or add additional context in comments.

5 Comments

This is not a good idea. malloc_usable_size queries the OS for the amount of memory it has allocated from a previous call to malloc. (Meaning it will be slow, and pointless, because you didn't already cache that information, even though you at some point had it when you called malloc.)
true, but desperate times seeks desperate decisions..
Personally I don't like the use of int for length and capacity. At the time of writing, I'd still wager a fiver on the conjecture that the majority of C programs currently running have a 16 bit int.
This describes appropriate practices, but it doesn't answer the actual question (which I take to be about how to implement function int arr_length(int arr[])).
Sadly I have to tell you, It is not possible, no way around it,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.