我得到了两个数组,然后将这两个数组合并到一个新创建的第三个数组中,它可以工作,但是当我输出数组的大小时,我得到的大小为“ 1”。我不理解为什么即使其中有5个元素,该数组的大小也为'1'。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr1[] = { 1,2,3 };
int arr2[] = { 9,4 };
int size1 = sizeof(arr1) / sizeof(int);
int size2 = sizeof(arr2) / sizeof(int);
int *arr = new int[size1 + size2];
//merging the two arrays by transferinng the elements into the third array
for (int i = 0; i < size1; i++)
{
arr[i] = arr1[i];
}
for (int i = size1; i < (size1 + size2); i++)
{
arr[i] = arr2[i - size1];
}
//sorting the array
sort(arr, arr + (size1 + size2));
cout << endl;
//finding the size of newly merged array
int mergeSize = sizeof(arr) / sizeof(int);
cout << "The size of the array is " << mergeSize << endl; //why am I getting the size of the array as '1'
return 0;
}
答案 0 :(得分:2)
sizeof(arr)
为您提供了指针arr
的大小,该大小与您为其分配的元素数量无关。
通过使用std::array
避免此问题。它没有std::vector
的开销,并且比C样式的数组更易于使用。
int main()
{
array<int, 3> arr1 = { 1, 2, 3 };
array<int, 2> arr2 = { 9, 4 };
array<int, arr1.size() + arr2.size()> arr;
//merging the two arrays by transferinng the elements into the third array
for (int i = 0; i < arr1.size(); i++)
{
arr[i] = arr1[i];
}
for (int i = 0; i < arr2.size(); i++)
{
arr[i + arr1.size()] = arr2[i];
}
//sorting the array
sort(arr.begin(), arr .end());
cout << endl;
//finding the size of newly merged array
int mergeSize = arr.size();
cout << "The size of the array is " << mergeSize << endl; //why am I getting the size of the array as '1'
return 0;
}
答案 1 :(得分:1)
arr
不是数组,而是一个指针,在指针上使用sizeof
会使指针的大小而不是它指向的动态数组的大小。 sizeof
指针通常为4或8,具体取决于您使用的是32位还是64位系统。
您可以通过使用向量而不是数组来避免这些问题。向量具有size
方法,该方法始终给出实际大小。数组在C ++中非常差。