Why does the compiler not pass the size of the char * arr [] array in the parameters?

Why does the compiler not pass the size of the char * arr [] array in the parameters? I wanted to get the size of the array passed by the parameter, but I think this will not work, because even char *a[] is char ** my question is, why is this so, 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]); } } 
+6
source share
5 answers

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

 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]); } } 
+7
source

This was a feature of C from the start and ported to C ++.

In the case of string arrays, the solution was to add a trailing null character to mark the end.

This 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.

+4
source

Since this is required by the C ++ standard, which inherited this behavior from C (and since C ++ wants to remain compatible with C).

As functional parameters, arrays fade into pointers.

You really want to use something like std::vector<std::string> . More on standard C ++ STL containers .

+3
source

C ++ is a language that provides a low level of access to system resources. The processor does not work with objects, but with memory addresses.

If you want predefined structures, use Java, C #, python or C ++ libs like stl.

0
source

In terms of language, your array has no 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 check the range.
The closest thing to the length of the array is the number of consecutive memory spaces that were allocated with a single call to new[] , but such information is only authoritative for the purpose of allocating and freeing memory: the "array" that you want to process into your function can only be part of one distribution (for example, you can allocate memory to load the entire text file and process each line separately).

0
source

All Articles