Answer the question
In order to leave comments, you need to log in
How to use sizeof in a function?
It is necessary to get sizeof
in the function the same as sizeof
in main()
.
On the Internet, I found only the option with , but I need to leave the ad exactly like that (although ... I definitely don’t need to use the second parameter, the rest is possible, but undesirable). And also to work for arrays of different sizes.
Help a freshman, please.void func(char (&a)[10])
void func(char *a)
#include <iostream>
using namespace std;
void func(char *a)
{
cout << "func sizeof(a)=" << sizeof(a);
}
int main()
{
char a[2][10]{ "test1","test2" };
cout << "sizeof(a)=" << sizeof(a[0]);
func(a[0]);
system("pause");
return 0;
}
Answer the question
In order to leave comments, you need to log in
If you need to calculate the size of a string, then use strlen. If the size of the string is in bytes, then multiply the result of strlen by sizeof from one char/
Arrays in C++ are one big lie. It's really just a bunch of data arranged sequentially in memory. At least some information about the type of an array can only be obtained if the array is static and is in the same scope as sizeof. Otherwise, it's just a pointer with no additional information. Therefore, most modern sources oppose the use of arrays.
You can do something like this to accept any arrays:
#include <iostream>
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_array<T>::value>::type
func(T& a)
{
std::cout << "func sizeof(a)=" << sizeof(a) << '\n';
}
int main()
{
char a[2][10]{ "test1","test2" };
std::cout << "sizeof(a)=" << sizeof(a[0]) << '\n';
func(a[0]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question