C++ 静态数组的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/453099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Size of static array
提问by Ron
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?
我声明了一个静态字符数组,然后将其传递给一个函数。如何获得编号。函数内部数组中的字节数?
采纳答案by Paul Dixon
You would have to pass it to the function. You can use sizeof() to get the size of an array.
您必须将其传递给函数。您可以使用 sizeof() 来获取数组的大小。
const char foo[] = "foobar";
void doSomething( char *ptr, int length)
{
}
doSomething(foo, sizeof(foo));
This MSDN pagehas explains more about sizeof and has a bigger example.
这个MSDN 页面解释了更多关于 sizeof 并有一个更大的例子。
Edit: * see j_random_hacker's answerfor an intriguing technique using templates... *
编辑:*请参阅 j_random_hacker 的答案,了解使用模板的有趣技术... *
回答by j_random_hacker
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.
此函数的新副本将针对调用它的每个不同大小的数组进行实例化,因此如果您使用许多不同大小的数组调用它,则会出现一些代码膨胀。但事实并非如此。
回答by Rocketmagnet
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.
不。不要使用数组。改用向量。现在几乎没有理由使用数组,因为它们是不安全的。AFAIK,它们是软件问题的主要原因之一,因为很容易意外地超出阵列的末尾。
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();
}
回答by Dawid Drozd
You can also use std::size()
from C++17
您也可以std::size()
从 C++17 使用
https://en.cppreference.com/w/cpp/iterator/size
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 ;)
对于 c++17 之前的复制示例实现;)
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
return N;
}
回答by Dawid Drozd
int array_size = sizeof(Array) / sizeof(Array[0]);
int array_size = sizeof(Array) / sizeof(Array[0]);
回答by abelenky
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.
你不能。C++ 中的数组是指针,这就是你所拥有的:指向数组开头的指针。如果它恰好是一个字符串,则可以使用 strlen 来测量其长度。如果是其他已知格式,则可以根据该格式计算长度。
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.
无论您的函数参数是 char[] 还是 char*,您都不知道大小。
I suggest passing the size in as a separate parameter.
我建议将大小作为单独的参数传入。
回答by lc.
One other option you have is creating a string class that manages the string. I'm sure someone out there has done this already. The most primitive version is a struct with a char * and the buffer length, where you have to manually manage the size whenever it changes. The other end of the spectrum is a fully implemented string class, with operator overloading and manupulation functions.
您拥有的另一种选择是创建一个管理字符串的字符串类。我敢肯定已经有人这样做了。最原始的版本是一个带有 char * 和缓冲区长度的结构体,你必须在它改变时手动管理大小。频谱的另一端是一个完全实现的字符串类,具有运算符重载和操作函数。
Then pass this class to your function and it already knows the size. It isn't really any different then passing it as a separate parameter; it simply is an easier way of managing strings if they're all different lengths.
然后将此类传递给您的函数,它已经知道大小。将它作为单独的参数传递并没有什么不同;如果它们的长度都不同,它只是一种更简单的管理字符串的方法。