determining the size of an array - c++

What is the appropriate function that shows how many are there in an array?
int a[10];
a[0] = 1;
a[1] = 3;
So I want something that shows size of a = 2.

There is no way to do this with raw arrays.
Consider a container class instead, such as std::vector:
std::vector<int> a;
a.push_back(1);
a.push_back(3);
std::cout << a.size() << "\n"; // Displays "2"

Sounds like you need a dynamically resizable array:
std::vector<int> a;
a.push_back(1);
a.push_back(3);
std::cout << a.size(); // 2

This array has 10 elements. You just happened to assign two of them but this doesn't change the size of the areay. If you want simething to keep track of the elements you set use std::vector<int> and push_back():
std::vector<int> array;
array.push_back(1);
array.push_back(3);
int size = array.size();

Oil Charlesworth seems to be right. The reason this is true is that when compiled a certain amount of memory is set aside (allocated) for that array no matter if it contains data or not. Therefore using a command like sizeof(a) will always yield the same result. It will return the amount of bytes allocated for your array. In this case the array is 40 bytes which makes sense because usually ints are 4 bytes long * length of the array (10) = 40.
This can differ from PC to PC though, at least, that's what I read in a tutorial a while back, the allocated size for each variable type seems to differ somewhat from PC to PC (or OS to OS).
ItÅ› not much help, I know, but now you at least know why you can't do it with raw arrays.

Related

How to count the number of elements in an predefined array

I want to count the actual number of elements in the array.
but if I use sizeof() statement it gives me the size of array. not the number of elements present.
int main()
{
int a[10],n;
a[0]=1;
a[1]=5;
a[2]=6;
n=sizeof(a)/sizeof(a[0]);
cout<<"The size of array " <<n;
}
Here it gives me the n value as 10 not 3. Please suggest me a way to derive the number of elements without affecting the performance.
int a[10]; // This would allocate 10 int spaces in the memory;
a[0] = 1; // You are changing whats inside the first allocated space, but you are not changing the number of items in your C array.
Solution 1 (Easy) :
#include <vector>
vector<int> a;
a.push_back(1);
a.push_back(2);
size_t size = a.size(); // to get the size of your vector. would return 2. size_t is the actual type returned by size() method and is an unsigned int.
Solution 2 (Complicated) :
You could create an int variable that you could call e.g. numberOfElements and update it each time you add an element.
This solution is actually used in the implementation of the vector class.
As it have been already mentioned, you should use std::vector or std:array to achieve this behaviour. Declaring simple array means you allocate enough memory on the heap. There is not a way to determine whether this memory is "occupied" with something valid or not, since there is always something (after allocation there are random values on each index of the array).

Allocate more memory for dynamically allocated array

My C++ algorithm obtains data with unknown size (it detects particles on the image one by one, and I cannot know how many particles will be detected before this algorithm finishes its work).
So, first I want to allocate, say, array with 10000 elements, and during the processing, if necessary, allocate another 10000 elements several times.
Here is what I tried, it doesn't work:
#include <iostream>
using namespace std;
int main(){
int n = 3;
int m = 3;
float *a = new float[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
float *b = a + 2;
b = new float[3];
b[0] = 4;
b[1] = 5;
cout << a[3] << endl;
}
As a result, I got minus infinity. Of course, I can handle this in different arrays, I can allocate a huge amount of memory once. I need to pass full array of detected data to the function after, so, as a result, I want to have one big array.
But still, is there a way to increase the size of your dynamically allocated way? What I want in a toy example is to increase number of elements in array a by 3, so it will have 6 elements.
In Matlab it is absolutely possible. What about C++?
Thanks
You should just use std::vector instead of raw arrays. It is implemented to grow efficiently. You can change its size with resize, append to it with push_back or insert a range (or various other things) with insert to grow it.
Changing the size of a manually allocated array is not possible in C++. Using std::vector over raw arrays is a good idea in general, even if the size does not change. Some arguments are the automated, leak-proof memory management, the additional exception safety as well as the vector knowing its own size.
No, you can't increase the size of an array. If you want to use an array, you'll have to allocate a new block, large enough for the whole new array, and copy the existing elements across before deleting the old array. Or you could use a more complicated data structure that doesn't store its elements contiguously.
Luckily, the standard library has containers to handle this automatically; including vector, a resizable array.
std::vector<float> a(3);
a[0] = 0;
a[1] = 1;
a[2] = 2;
// you can resize it by specifying a new size
a.resize(4);
a[3] = 3;
// or by appending new elements
a.push_back(4);
You should use a vector and then resize when necessary or let it grow by itself.
When you do:
float *b = a + 2;
b = new float[3];
the memory allocated will not be allocated contiguously to the first allocation even if you previously set the pointer to point at the end(it will be overwritten anyway). Therefore, when accessing a[3], you get out of bound.

Is there any built in method in c++ to findout length of an array?

like array.length in java is there any built in method in c++ to findout size of an array?
I know about length(). but it only works for strings only ...
And i tried this ...
int a[10];
a[0]=1;
a[1]=2;
print(sizeof(a)/size(a[0]))
but it gives output as 10 but is there a way getting only 2 as output
If you're using C++, don't use arrays, use std::vector instead (especially if you need the count of currently held items, not the container's capacity). Then you can write:
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
printf("%d\n", vec.size());
int a[10];
declares an array of 10 ints; sure, you're only initialising the first two, but the other 8 are still there, they're just (probably) filled with junk at the moment.
To do what you want, you should use a std::vector instead. You can then do this:
std::vector<int> a;
a.push_back(1);
a.push_back(2);
std::cout << a.size() << std::endl; // prints 2
Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size.
In an array of 10 ints, when it is declared, memory is allocated for 10 int values. even if you initialize just two, the rest of it contains some junk values and the memory remains allocated.
If you want the used size, your best bet is to use std::vector.
if you want to know the number of elements in an array you can do this
int array[3] = {0, 1, 2};
int arraylength = sizeof(array)/ sizeof(*array);
Sure. It's name is vector::size. It doesn't apply to C-style arrays, only to std::vector. Note that Java's Array class is also not a C-style array.

why constant size of struct despite having a vector of int

I have defined a struct which contains a vector of integer. Then I insert 10 integers in the vector and check for the size of struct. But I see no difference.
Here is my code:
struct data
{
vector<int> points;
}
int main()
{
data d;
cout << sizeof(d) << endl;
for (int i=0; i< 10; ++i)
d.points.push_back(i)
cout << sizeof(d) << endl;
In both the cases I am getting the same result : 16
Why is it so? Shouldn't the size of struct grow?
A vector will store its elements in dynamically allocated memory (on the heap). Internally, this might be represented as:
T* elems; // Pointer memory.
size_t count; // Current number of elements.
size_t capacity; // Total number of elements that can be held.
so the sizeof(std::vector) is unaffected by the number of elements it contains as it calculating the sizeof its contained members (in this simple example roughly sizeof(T*) + (2 * sizeof(size_t))).
The sizeof operator is a compile time operation that gives you the size of the data structure used to maintain the container, not including the size of the stored elements.
While this might not seem too intuitive at first, consider that when you use a std::vector you are using a small amount of local storage (where the std::vector is created) which maintains pointers to a different region holding the actual data. When the vector grows the data block will grow, but the control structure is still the same.
The fact that sizeof will not change during it's lifetime is important, as it is the only way of making sure that the compiler can allocate space for points inside data without interfering with other possible members:
struct data2 {
int x;
std::vector<int> points;
int y;
};
If the size of the object (std::vector in this case) was allowed to grow it would expand over the space allocated for y breaking any code that might depend on its location:
data2 d;
int *p = &d.y;
d.points.push_back(5);
// does `p` still point to `&d.y`? or did the vector grow over `y`?

C++ getting the size of an array

I'm new to programming and I was wondering, how to get the size of an array, that is, get the size of how many elements are inside the array. For example if I declare an array of size 10, but only input 3 elements into the array, how would I determine the size of this array? If I don't know how many elements I placed in initially.
If you declare an array, e.g. int array[10], then its size is always 10 * sizeof(int). There is no way to know how many times you've accessed it; you'd need to keep track of that manually.
You should consider using container classes, e.g. std::vector:
std::vector<int> vec;
vec.push_back(5);
vec.push_back(10);
vec.push_back(42);
std::cout << vec.size() << "\n"; // Prints "3"
If you declare an old-style array of 10 elements, e.g. std::string words[10], the size of the array is always 10 strings. Even with the new style (std::array), it would be a fixed size.
You might be looking for a std::vector<>. This doesn't have a fixed size, but does have a .size() method. Therefore, if you add three elements to it, it will have .size()==3
to get the array size (in number of elements) assuming you do not know it in advance
use sizeof(a)/sizeof(a[0])
see the below example program. I used C but it should carry over to C++ just fine
#include <stdio.h>
int main(){
int a[10];
printf("%d elements\n",sizeof(a)/sizeof(a[0]));
return 0;
}
//output: 10 elements
There's several possible ways, but they depend on your definition.
If you know there is a value the user won't input (also known as a sentinel value), you can use a function like memset, to set the entire array to that unused value. You would then iterate through the list counting all the variables in the list that don't match that value.
The other way is to build your own array class, which counts whenever the array is modified (you'd have to overload the = and [] functions as appropriate).
You could also build a dynamically linked list, so as the user adds variables, the count can either be determined by walking the list or keeping count.
But, if you're taking the array as the basic array, with no idea as to it's actual starting state, and no idea what to expect from the user (given this is your program, this shouldn't occur), then generally speaking, no, there is known way to know this.
You maintain a counter variable count initialized to 0.
Whenever you are adding to array increment the count by 1.
Whenever you are removing from array decrement the count by 1.
anytime count will give you the size of the array.
Suggestion:
int[10] arr;
//init all to null
for (int i =0; i < 10; i++)
arr[i] = 0;
arr[0]=1;
arr[2]=5;
int sz = 0;
for (int j = 0; j < 10; j++)
if (arr[j] != 0) sz++;