Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler doesn't pass size of array char *arr[] in parameters?

Tags:

c++

arrays

c++11

Why compiler doesn't pass size of array char *arr[] in parameters? I wanted to get get size of array passed by parameter but I guess it doesn't work because even char *a[] is char ** my question is why is it and can I make it work?

#include <stdio.h>
#include <stddef.h>
#include <stdio.h>

template<class T, size_t len>
constexpr size_t lengthof(T(&)[len])
{
    return len;
}
void printarr(const char *a[]);

int main()
{
    const char *a[] = { "aba", "bd", "cd" };
    printarr(a);
}

void printarr(const char *a[])
{
    for(size_t i = 0, c = lengthof(a); i < c; i++) {
        printf("str = %s\n", a[i]);
    }
}
like image 719
The Mask Avatar asked Mar 30 '14 02:03

The Mask


People also ask

Why arrays are not passed by value?

The reason you can't pass an array by value is because there is no specific way to track an array's size such that the function invocation logic would know how much memory to allocate and what to copy. You can pass a class instance because classes have constructors. Arrays do not.

Why can't you change the size of an array?

If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

Why sizeof is not working?

Because `sizeof(a)` is referring to `a` as a pointer rather than an array. In C an array's length must be passed separately because it is not remembered within the array. in short.. when you pass a[] in a function it will decay into pointer to an int .

Why do we often need to pass the size of an array as a parameter to a function?

Passing the array size tells the function where the bounds are so you can choose not to go beyond them.


1 Answers

You can make it work by using the same trick you used in your lengthof function template.

template<size_t len>
void printarr(const char* (&a)[len])
{
    for(size_t i = 0, c = lengthof(a); i < c; i++) {
        printf("str = %s\n", a[i]);
    }
}
like image 188
Benjamin Lindley Avatar answered Oct 03 '22 06:10

Benjamin Lindley