问题描述
那么这条线是什么意思? int n = sizeof(arr) / sizeof(arr[0]) 为什么要用arr[0]除arr,这里n有什么用?
#include <iostream>
using namespace std;
int search(int arr[],int n,int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2,3,4,10,40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr,n,x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
解决方法
来自 C++ 14 标准 (5.3.3 Sizeof)
1 sizeof 运算符产生对象中的字节数 其操作数的表示...
如果你有一个这样声明的数组
int arr[] = { 2,3,4,10,40 };
然后是表达式
sizeof( arr )
产生整个数组占用的内存大小。
表达式
sizeof(arr[0])
是数组中每个元素的大小,因为数组的所有元素都具有相同的大小。由于数组元素的类型是 int
那么你也可以写
sizeof( int )
代替
sizeof( arr[0] )
所以表达式
sizeof( arr ) / sizeof( arr[0] )
产生数组中元素的数量。
这是一个演示程序。
#include <iostream>
int main()
{
int arr[] = { 2,40 };
size_t size_of_array = sizeof( arr );
std::cout << "The size of the memory occupied by the array is "
<< size_of_array << '\n';
size_t size_of_element = sizeof( arr[0] );
std::cout << "The size of the memory occupied by each element of the array is "
<< size_of_element << '\n';
std::cout << "The number of elements in the array is "
<< size_of_array / size_of_element << '\n';
return 0;
}
程序输出为
The size of the memory occupied by the array is 20
The size of the memory occupied by each element of the array is 4
The number of elements in the array is 5
注意表达式的值是size_t
类型而不是int
类型。
如果您的编译器支持 C++ 17,那么您可以使用标头 std::size
中声明的标准函数 <iterator>
而不是表达式 sizeof( arr ) / sizeof( arr[0] )
,例如
#include <iterator>
//...
size_t n = std::size( arr );
至于函数搜索则应该像这样声明和定义
size_t search( const int arr[],size_t n,int x )
{
size_t pos = 0;
while ( pos < n && arr[pos] != x ) ++pos;
return pos;
}
并且在主要你应该写
size_t pos = search(arr,n,x);
( pos == n )
? cout << "Element is not present in array.\n"
: cout << "Element is present at index " << pos << '\n';
,
该行决定了数组的大小。在 C/C++ 数组中(与 Java 相比),大小不可用。由于 n 个元素的数组使用单个元素大小的 n 倍,因此您可以像这样计算元素的数量。 当使用在编译时未知数组元素实际大小的模板时,这更有意义。