N
N
never_mind2015-10-18 10:53:27
C++ / C#
never_mind, 2015-10-18 10:53:27

How to use sizeof in a function?

It is necessary to get sizeofin the function the same as sizeofin 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

4 answer(s)
N
never_mind, 2015-10-18
@never_mind

need array size

G
GavriKos, 2015-10-18
@GavriKos

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/

M
MiiNiPaa, 2015-10-18
@MiiNiPaa

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

A
abcd0x00, 2015-10-19
@abcd0x00

Typically, C++ uses vector for this purpose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question