Reputation: 17427
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]);
}
}
Upvotes: 6
Views: 324
Reputation: 1270
From the point of view of the language, your array doesn't have a length; the compiler cannot read your mind and decide where the array begins and where it ends, and it cannot waste memory and processing to perform range checking.
The closest thing to an array length is the number of consecutive memory spaces that have been allocated by a single new[]
invocation, but such information is only authoritative for the purpose of allocating and deallocating memory: the "array" you want to process in your function might be only a portion of a single allocation (for example, you might allocate memory to load a whole text file and process each line separately).
Upvotes: 0
Reputation: 103693
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]);
}
}
Upvotes: 7
Reputation: 5147
C++ is a language what provides low level access to system resources. Processor is not working with objects, but with memory addresses.
If you want predefined structures, use Java, C#, python, or c++ libs like stl.
Upvotes: 0
Reputation: 21617
That has been a feature of C since the beginning and carried through into C++.
In the case of string arrays, the solution has been to add a trailing null character to mark the end.
The was probably done for the sake of efficiency when C started on ancient PDP computers.
Use strlen; or better yet std::string or std::vector.
Upvotes: 4
Reputation: 1
Because this is required by the C++ standard, which inherited this behavior from C (and since C++ wants to stay compatible with C).
As function parameters, arrays are decayed into pointers.
You really want to use something like std::vector<std::string>
instead. Learn more about standard C++ STL containers.
Upvotes: 3