Size of static array

36,756

Solution 1

You would have to pass it to the function. You can use sizeof() to get the size of an array.

const char foo[] = "foobar";

void doSomething( char *ptr, int length)
{

}


doSomething(foo, sizeof(foo));

This MSDN page has explains more about sizeof and has a bigger example.

Edit: * see j_random_hacker's answer for an intriguing technique using templates... *

Solution 2

Use a function template instead that has a non-type template parameter:

template <size_t N>
void func(char (&a)[N]) {
    for (int i = 0; i < N; ++i) {
        cout << "a[" << i << "] = " << a[i] << endl;   // Or whatever you want to do
    }
}

To call:

char myArray[500];        // Or "static char myArray[500]", if you want
func(myArray);

A new copy of this function will be instantiated for each distinct size of array that it is called with, so if you call it with many different-sized arrays, you'll get some code bloat. But that's not likely to be the case.

Solution 3

You can also use std::size() from C++17

https://en.cppreference.com/w/cpp/iterator/size

#include <iostream>
#include <vector>
#include <iterator>

int main() 
{
    std::vector<int> v = { 3, 1, 4 };
    std::cout << std::size(v) << '\n'; 

    int a[] = { -5, 10, 15 };
    std::cout << std::size(a) << '\n';
}

For pre c++17 copy sample implementations ;)

template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
    return N;
}

Solution 4

No. Don't use arrays. Use a vector instead. These days there is almost no excuse for using arrays because they are unsafe. AFAIK, they are one of the main reasons for software problems because it's so easy to accidently overrun the end of the array.

Using a vector, you don't have to worry any more about buffer overruns. And your function can easily find out the size of the vecor.

#include <vector>
vector<char> myVector;

void DoSomething(vector<char> &v)
{
    int sizeOfVector = v.size();
}

Solution 5

You can't. Arrays in C++ are pointers, and that is all you have: the pointer to the beginning of the array. If it happens to be a string, you can use strlen to measure its length. If its some other known format, you can calculate the length according to that format.

Consider this code:

static char str[] = "hello world";

foo(str);
bar(str);

void foo(char* str)
{
   // length of str is unknown
}

void bar(char str[])
{
  // length of str is still unknown
}

Regardless of if your function parameter is a char[] or a char*, you don't know the size.

I suggest passing the size in as a separate parameter.

Share:
36,756
Ron
Author by

Ron

Software Developer

Updated on October 18, 2020

Comments

  • Ron
    Ron over 3 years

    I declare a static char array, then I pass it to a function. How to get the no. of bytes in the array inside the function?

  • Ankit Roy
    Ankit Roy over 15 years
    Your answer is correct for C, but in C++ you can define a function template that does "discover" the size of a static array.
  • Ankit Roy
    Ankit Roy over 15 years
    You're on the right track, but why invent your own string class when std::string already exists and does exactly what is needed?
  • brainfck
    brainfck over 14 years
    You should divide the length through 8! sizeof() returns the number of bits - not bytes.
  • int3
    int3 over 14 years
    @brainfck: ... no. See msdn.microsoft.com/en-us/library/0w557fh7(VS.80).aspx for confirmation.
  • fmuecke
    fmuecke almost 14 years
    Nice! template<typename T, size_t N> size_t elments_of_array( T (&arr)[N] ) { return N; }
  • Georg Fritzsche
    Georg Fritzsche over 13 years
    @fmuecke: In that case better go compile-time - see this question.
  • Cris Luengo
    Cris Luengo over 3 years
    "it's so easy to accidently overrun the end of the array." This is no different than for a vector.
  • Rocketmagnet
    Rocketmagnet almost 3 years
    @CrisLuengo - That's true, but at least vectors give you: A) access to .size(), and B) auto iteration. With an array, you're relying on the programmer to implement some external mechanism to keep track of the size of the array, and this can easily be broken.
  • Sandburg
    Sandburg over 2 years
    There shouldn't be parenthesis in this usage. sizeof(type) = for types ; sizeof expression = for variables