simple question

R

Rolf Magnus

Kitty said:
Given a integer array. How can I know the total size of this array?
Thanks.

#include <iostream>

int main()
{
int arr[100];
std::cout << "Size in bytes: " << sizeof(arr) << '\n';
std::cout << "Number of elements: " << sizeof(arr)/sizeof(*arr) << '\n';
}
 
B

Bryan Hackney

Kitty said:
Given a integer array. How can I know the total size of this array? Thanks.

sizeof( array ) / sizeof( int )

It's a compile time thing.
 
K

Kitty

thanks.


Rolf Magnus said:
Kitty said:
Given a integer array. How can I know the total size of this array?
Thanks.

#include <iostream>

int main()
{
int arr[100];
std::cout << "Size in bytes: " << sizeof(arr) << '\n';
std::cout << "Number of elements: " << sizeof(arr)/sizeof(*arr) << '\n';
}
 
J

Jonathan Turkanis

Kitty said:
Given a integer array. How can I know the total size of this array? Thanks.

Here's another way, which could be described as "cutting a daisy with a
daisy-cutter":

#include <iostream>
#include <boost/range/detail/sizer.hpp>

int main()
{
int arr[100];
std::cout << "Size in bytes: " << sizeof(arr) << '\n';
std::cout << "Number of elements: " << sizeof( boost::sizer(arr) ) << '\n';
}

Jonathan
 
J

Jon Bell

Kitty said:
Given a integer array. How can I know the total size of this array?
Thanks.

#include <iostream>

int main()
{
int arr[100];
std::cout << "Size in bytes: " << sizeof(arr) << '\n';
std::cout << "Number of elements: " << sizeof(arr)/sizeof(*arr) << '\n';
}

Kitty should beware that if she passes the array to a function, this
method will not work inside the function. Inside the function, all you
have is a pointer to the array, so sizeof(arr) simply returns the size of
the pointer itself. In fact, inside the function there is no way to find
out the "actual" size of the array, except by passing it to the function
as a separate parameter. This is one reason why std::vector should be
preferred to arrays, except in situations that require arrays for some
good reason.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

A simple form question 2
Tasks 1
Simple question 1
Simple Program 0
Understanding an exercise about sub-sums in arrays 1
Minimum Total Difficulty 0
Simple question python 2
Simple Test Framework 0

Members online

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top