c++ - find number of element of array when it use as parameter in C++
问题描述
I write a function in c++ that should count number of elements an array has. function receive array as its parameter. so I try the following method:
int countArray(int a[])
{
int size = 0;
while(a[size] != NULL)
{
size++;
}
cout<<"number of array elements are : "<<size<<endl;
}
this function work but not perfectly. when i pass an array to this function which has same number of elements as its size int one[3] = {1,2,3}
or an unsized array it will return result with one more element. for example for the previous array one[3]
it will display number of array elements are 4.
but in other situation it work fine. for example if I pass an array that has less element than its size int two[4] = {1,2,3}
it will work.
I should use array in this example not vector or struct , so what should i do or what is the reason that function doesn't work with that kind of array as its parameters.
解决方案
Once an array have decayed to a pointer (to its first element), there's no way of getting its size.
The loop you have can (and most likely will) go out of bounds and you will have undefined behavior.
There are three possible solutions:
Use
std::array
insteadUse
std::vector
insteadUse array-size deduction with templates:
template<size_t N> int countArray(int (&a)[N]) { ... }
Also note that C++ doesn't have the concept of "null" values. The symbolic constant NULL
is for pointers only.
推荐阅读
- c# - 如何为组合框使用类似 ReadOnly 的样式
- javascript - 如何在 Angular 6 中使用异步获取 JSON 对象中的数据集合?
- java - java.text.annotation 有什么用?我已经参考了 java 文档,但无法掌握
- android - 移动设备中的 OpenSeaDragon FullScreenMode
- python - 如何永久停止并行运行的 django 后台任务?
- node.js - 在 Sequelize 中添加具有起始值的自动递增整数
- javascript - 如何防止表单通过 AJAX 验证提交
- azure-api-management - 2 个位置无法访问 Azure API 管理后端
- jenkins - 重启 Jenkins 流水线并调整参数
- python - 如何查找旧的大文件并为包含这些文件的目录生成指标