0

So ive been making arrays this way but i found a error, lets say it was a loop that copied and array element by element:

int v1[] = { 3, 4, 7, 8};
int v2[sizeof(v1)];
for (auto i = 0; i < sizeof(v2); ++i)
{
  v2[i] = v1[i]
}

The v2 array will not have the size of 4 integers, it adds them all up. So v2 would have the size of 22 not 4 integers. So i was wondering if there was any way of finding the size of an array without having to go to the array and see how many there elements there are manually. Is there a way? thanks.

Harry the hacker
  • 309
  • 1
  • 5
  • 11
  • Just change `sizeof(v1)` and `sizeof(v2)` to `sizeof(v1)/sizeof(int)` and `sizeof(v2)/sizeof(int)` or `sizeof(v1)/sizeof(v1[0])` and `sizeof(v2)/sizeof(v1[0])` – DimChtz Apr 15 '16 at 00:22
  • sizeof(v1) returns total byte size of memory under array, not count of int's. – Ivan Apr 15 '16 at 01:26

2 Answers2

3

Just use std::array or std::vector:

std::array<int, 4> v1 { 3, 4, 7, 8};
auto v2 = v1;

Live demo

Shoe
  • 74,840
  • 36
  • 166
  • 272
2

While I agree with the rest that you should use STL containers in general, in your case you can get the count of the elements in the array by using sizeof(v1)/sizeof(int). sizeof(v1) will give you the total number of bytes for a 4 integer array and dividing by sizeof(int) will give you the number of elements.

Jarod42
  • 203,559
  • 14
  • 181
  • 302