SizeOf question C++ | SoloLearn: Learn to code for FREE!

0

SizeOf question C++

I have a question about this code https://code.sololearn.com/c8fswm6Kkx2g/#cpp. I am wondering what is happening when I use the sizeof operator on the array "arr" it output 24 which is not even in the sequence. As well as when I use the sizeof operator on the "arr[0]" it outputs 4 even though the first number in the sequence is 10. This is very confusing to me if you could help explain this to me that would be wonderful, thank you.

6/9/2018 9:07:12 AM

Bradley

5 Answers

New Answer

+7

It is pretty much obvious that you wanted to initialize a vector of integers using an array of integers by incorporating pointer arithmetic which is a little bit messy in terms of readability but good for compatibility with C++98/03. For C++11 compliant implementations, you'd simply use iterators for initializing a vector by another container or in simplest form as the way you initialize an ordinary array directly. Consider the following examples. // initialize vector using assignment operator (C++11) std::vector<int> vec = {10, 20, 30, 40, 50}; // initialize vector using iterator and another container (C++11) int arr[] = {10, 20, 30, 40, 50}; std::vector<int> vec(std::begin(arr), std::end(arr)); // initialize vector using pointer arithmetic and another container (Both C++11 and C++98/03) int arr[] = {10, 20, 30, 40, 50}; std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0])); All three of them yield the same result with different methods which is usually dictated by implementation and project restraints.

+6

Sizeof returns the size of an element in the memory in bytes. The compiler uses 32 bit integers, which are 4 bytes large (32/8=4). The array contains 6 integers: 6*4=24

+2

Aaron Eberhardt isn‘t the name of the array basically just a pointer? if so why doesn‘t sizeof(a) return the size of pointers on the system but the lenght of the array

0

Thank you very much :)

0

Max I guess because C++ knows the array size and also that this must be a pointer to an array. Using an usual pointer instead just returns the pointers size, so these pointers must be treated differently