-3

Is there a way I could get the length of an array inside a function? I need to find the size of an array, however it is defined in the main function and I cannot pass the array size as an argument as I cannot change the main function. So is there any way to find it through the function?

The array's max size is set to be roughly 100, however the actual input will be anywhere between size 1 - 20. So I can't really take the max size approach either.

phuclv
  • 37,963
  • 15
  • 156
  • 475
TheKingSid
  • 39
  • 6
  • 1
    If you are going to pass an array to your Function this means that it is a function which are you going to implement it yourself. If is so, why do you need to find its length inside that function? Anyway probably with a sentinel at the end, or using a char array and check the input to be only integers or whatever. – Michi Apr 18 '20 at 09:04
  • Does your function have the declaration of the array in scope? Is the array dynamically allocated? Show us some code! – Jens Apr 18 '20 at 09:06
  • 1
    A little of code with the interface of the function could help. Anyway, what you ask is unfortunately impossible unless, as @Michi wrote above, you define a special content for the last element of the array. Just like it happens with strings, that are sequences of chars terminated by a `'\0'`. – Roberto Caboni Apr 18 '20 at 09:09
  • The function has only been passed the array but no deceleration whatsoever. The array is not dynamically allocated either @Jens – TheKingSid Apr 18 '20 at 09:15
  • I followed what @JosephBalestrin suggested. Made a for loop and executed it till my array returns '\0' and it worked :D – TheKingSid Apr 18 '20 at 09:17
  • 3
    ...and showing us the code is impossible, because...? – Jens Apr 18 '20 at 09:17
  • @TheKingSid if your array is really string then there's no reason to not use `strlen()` – phuclv Apr 18 '20 at 09:37
  • @TheKingSid You should not use that approach as it is harmful. Consider when no element has the value `0` /`\0`. Then the function will use an array length longer than the real one. Attempt to write or read in this array invokes undefined behavior. If you want to use that approach you need reserve one element at the end of the array which is initialized to zero and not changed in anyway. – RobertS supports Monica Cellio Apr 18 '20 at 09:51

3 Answers3

2

No, arrays always decay to pointers when passing into functions so you must pass the length in if you want the function to know the size. With some preconditions you have multiple ways to do that without an additional parameter:

  • Add a null/zero/whatever special parameter at the last, similar to a null-terminated char array. This is only possible if you really know there's a unique value that never appears in the value list to put at the final position. This method is actually very common in Linux system calls, for example the exec family

    char *args[] = { "Hello", "C", "Programming", NULL /* ends the array */ };
    execv("./hello", args);
    
  • Add a length prefix at the beginning

    void my_function(int array[])
    {
        int length = array[0];
        int* data = &array[1];
        // operate on data[];
    }
    
    int my_data[LENGTH + 1] = { LENGTH, /* values */ };
    my_function(my_data);
    

    Pascal also uses length-prefixed string, so its string is limited to only 255 characters with a 1-byte length. But this can be fixed by using a bigger length

    A variation of this is BSTR in Windows where the pointer points to the actual data instead of start of the struct

    typedef struct MY_ARRAY
    {
        int32_t length;
        my_type* data;  // array of the desired type
    } my_array;
    
    void my_function(my_type array[])
    {
        int length;
        memcpy(&length, (char*)array - sizeof(int32_t), sizeof(int32_t));
        // operate on array[];
    }
    
    my_type data_list[] = { /* some data */ };
    my_array my_data = { LENGTH, data_list };
    my_function(my_data.data);
    
phuclv
  • 37,963
  • 15
  • 156
  • 475
1

if the function is declared for example like

void f( T a[] );

where T is some type specifier then the function deals with a pointer to the type T. That is the above declaration is equivalent to the following declaration

void f( T *a );

and the both declare the same one function.

So the only way to calculate the number of actual elements in the array pointed to by the pointer is to introduce a sentinel value that will differ from values of actual elements of the array.

For example a character array can have such a sentinel value like '\0' that is when a character array contains a string.

An array of strings can have as a sentinel value either an empty string "" or depending on how it is declared (for example as an array of element type char *) the sentinel value can be NULL.

For integer arrays you have yourself to select an appropriate value as a sentinel value. For example if actual elements are non-negative then the sentinel value can be set to -1.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-5

You could include a for loop with a counter to see how many variables there are before the the next line.

int counter(int array[100]) {
    int counter = -1;
    for (i = 0; array != '\0'; i++) {
        counter = counter + 1;
    }
    return counter;
}

and then in the main section

int arraysize = counter();
Jens
  • 69,818
  • 15
  • 125
  • 179
Joseph B
  • 18
  • 5
  • What happen if array[0] == 0 ? – Michi Apr 18 '20 at 09:05
  • 1
    I am assuming the question is asking for a prompt from the user, otherwise, I do not think this code will work :/ – Joseph B Apr 18 '20 at 09:10
  • 1
    This solution could work for an array of characters correctly initialized, but absolutely not for an array of integers. NO WAY. – Pierre François Apr 18 '20 at 09:18
  • 1
    This looks like a strlen, since you are looking for the string terminator, but it won't work in the general scenario. Looking for a terminator is almost the only one solution, and honestly saying it it could have been an acceptable answer, but in that case you should have also provided an example of a terminator in an array of structures. – Roberto Caboni Apr 18 '20 at 09:20
  • What if the array does not contain an element with `0`? Then you already seeking beyond the bounds of the array, resulting in returning a length which is longer than the original array. If the user attempts to access parts of that not existing array part, you have undefined behavior. – RobertS supports Monica Cellio Apr 18 '20 at 09:44