How to display the number of elements in a dynamic memory allocated array

Hi,

Please, can someone help with this code? I have been trying to display the number of elements store in a dynamic memory allocated 1D array created using new but kept getting segmentation error (Please see below).

Your help will be greatly appreciated. Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>

using std::cout;
using std::endl;

int main()
{
	int N{100};       // Initializing variable for size of array

	int *v;            // Declaring a pointer to the integer array

	v = new int [N+1];    // Allocating memory of size N+1

	int arraySizeBytes{0};    // Total size of the array in bytes

	int elementSizeBytes{0};    // Size of an individual element in bytes

	int counter{0};    // Number of elements in the array
	
	v[1] = 7; v[2] = -3; v[3] = 1;    // Initialize and store value in elements of array

    cout << "Values stored in the array:" << endl;

	for (int i = 0; 1 < N; i++)
	{
		if(v[i] != 0)
		{
			cout << v[i] << "\n";    // Print value of each element in the array
		}
	}


	delete [] v;        // Free up memory

	return 0;
}


Sample output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Values stored in the array:
7
-3
1
1041
825503793
959918896
1701972534
1852383332
1701344288
1920098592
171604321
60337
Segmentation fault
Last edited on
main.cpp:24:22: warning: variable 'N' used in loop condition not modified in loop body [-Wfor-loop-analysis]
        for (int i = 0; 1 < N; i++)
                            ^
main.cpp:14:6: warning: unused variable 'arraySizeBytes' [-Wunused-variable]
        int arraySizeBytes{0};    // Total size of the array in bytes
            ^
main.cpp:16:6: warning: unused variable 'elementSizeBytes' [-Wunused-variable]
        int elementSizeBytes{0};    // Size of an individual element in bytes
            ^
main.cpp:18:6: warning: unused variable 'counter' [-Wunused-variable]
        int counter{0};    // Number of elements in the array
            ^
4 warnings generated.


Check your warnings.

> for (int i = 0; 1 < N; i++)
You used one rather that i in your loop condition.
So your loop runs forever (or until the OS has had enough).

Line 24 says for (int i = 0; 1 < N; i++)
This loop will continue while the number one is less than N.
You probably meant to type the letter i, as in
for (int i = 0; i < N; i++)

I have been trying to display the number of elements stored in an array

An array of 100 elements stores 100 elements by definition. For example
int* a = new int[100];
Creates an array of 100 ints. It does not merely get memory for 100 ints, leaving the memory empty, but actually creates all 100 of them.

You can choose to use fewer than all 100, but you have to keep track of how many you are using on your own:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>

using std::cout;
using std::endl;

int main()
{
    // The "capacity" is the maximum number of elements that can be in use at one time.
    // The "size" is the number of elements that are currently in use.
    // These values are in elements, not bytes.  This terminology (size vs. capacity) 
    // comes from the C++ standard library.
    
    // For example, if the size was 10, the first 10 elements of the array
    // should be "in use".
    
    // The size must never be greater than the capacity, because it 
    // makes no sense to e.g., use 101 elements of an 100-element array.
    int capacity{100}; 
    int size{};        

    // create an array of 100 ints.
    // The variable v points to the first element in this array.
    // Note that this array contains exactly 100 ints, numbered 0 through 99
    int* v = new int [capacity];

    // int array_element_size_in_bytes = sizeof(v[0]); // or: sizeof(int)
    // int array_size_in_bytes = capacity * array_element_size_in_bytes;    

	// array elements start at 0.  Every time the next element should be marked as "in use", 
	// increase the count of "elements in use" by one.
	v[size] =  7;  ++size;  // or: v[size++] = 7;
	v[size] = -3;  ++size;
	v[size] =  1;  ++size;
    cout << "Values stored in the array:" << endl;

	for (int i = 0; i < size; ++i)
	{
	  cout << v[i] << "\n";
	}

	delete[] v;
}

https://coliru.stacked-crooked.com/a/1b59f84dc0712166
Manual memory management is so C. C++ has dynamic memory management with std::vector. A vector keeps track of the number of elements, and manages the memory for you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include <vector> // https://en.cppreference.com/w/cpp/container/vector

int main( )
{
   std::vector<int> v;

   v.push_back(7);
   v.push_back(-3);
   v.push_back(1);

   std::cout << "The size of the vector is: " << v.size( ) << '\n';

   std::cout << "Values stored in the array:\n";

   for ( unsigned i = 0; i < v.size( ); i++ )
   {
      std::cout << v[ i ] << '\t';
   }
   std::cout << "\n\n";

   std::cout << "Let's try that again\nValues stored in the array:\n:";

   // range-based for loop makes it easier to access every element
   // https://en.cppreference.com/w/cpp/language/range-for
   for ( const auto& i : v )
   {
      std::cout << i << '\t';
   }
   std::cout << '\n';
}

http://coliru.stacked-crooked.com/a/426fcb4c44a0cb0c
In C and C++ arrays (and vectors) are zero-based. The first element is v[ 0 ], not v[ 1 ].

Another way to access all of a vector's element is to use a vector's iterators.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include <vector> // https://en.cppreference.com/w/cpp/container/vector

int main( )
{
   std::vector<int> v;

   v.push_back(7);
   v.push_back(-3);
   v.push_back(1);

   std::cout << "The size of the vector is: " << v.size( ) << '\n';

   std::cout << "Values stored in the array:\n";

   // using a vector's begin/end iterators
   // cbegin/cend so the elements can't be altered)
   for ( auto i = v.cbegin( ); i != v.cend( ); ++i )
   {
      std::cout << *i << '\t';
   }
   std::cout << '\n';
}

http://coliru.stacked-crooked.com/a/fd6e52cc524d4de4
@All

Thanks guys!!!

Sorry, the for loop statement in the initial code has a typo which you rightly spotted.

I'd read up your notes as well as those links you have included and get back to you if I have further questions.

By the way, thanks for the other time as well.

Great seeing you all again.
Using new/delete then consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using std::cout;

using E = int;		// Type of array elements

int main() {
	constexpr size_t N { 100 };					// Number of elements in the array (accessed 0 to N - 1)
	constexpr size_t elementSizeBytes { sizeof(E) };		// Size of an individual element in bytes
	constexpr size_t arraySizeBytes { N * elementSizeBytes };	// Total size of the array in bytes
	const auto v { new E[N]{} };					// Allocate array of size N elements
	size_t counter { };						// Number of non-zero elements in the array

	v[1] = 7; v[2] = -3; v[3] = 1;					// Initialize and store value in elements of array

	cout << "The array has " << N << " elements\n";
	cout << "Each element uses " << elementSizeBytes << " bytes\n";
	cout << "The total size of the array is " << arraySizeBytes << " bytes\n\n";
	cout << "Non-zero values stored in the array are:\n";

	for (size_t i {}; i < N; ++i)
		if (v[i]) {
			++counter;
			cout << v[i] << '\n';		// Print value of each element in the array
		}

	cout << "\nThere are " << counter << " non-zero elements\n";

	delete[] v;							// Free up memory
}



The array has 100 elements
Each element uses 4 bytes
The total size of the array is 400 bytes

Non-zero values stored in the array are:
7
-3
1

There are 3 non-zero elements
Last edited on
@All:

It worked well. Thank you all for your help and contribution.

Please as a follow up question, one of the reasons I felt compelled to ask was after reading a similar question here: https://stackoverflow.com/questions/19200263/how-to-find-number-of-elements-in-dynamic-array

I know it was posted a long time ago but it's a bit puzzling still, especially since it appears that other users suggested that finding the number of elements in dynamically allocated array was not possible.

Isn't that similar to what was just executed above here or are they talking about something different altogether?

If the latter is the case, how would you suggest one gets around this?

Thank you all.
The difference is that you already know how many elements there are and just count how many of them that don't have the value 0. Note that putting {} after new int[N], like seeplus did, zero-initializes the int elements.

The discussion that you linked to talks about finding the number of elements in the array (regardless of value) which is not possible.

The way around it is to store the size separately, or use std::vector which takes care of it for you. I highly recommend the latter.
Last edited on
@Peter87:
Thank you. Just out of curiosity: Is it possible to write the code such that it increases the size of the dynamically allocated array by one (1) while the program is running just so that the number of elements don't exceed the maximum size that was previously allocated?

P.s.: I would use std::vector as recommended. Thanks
Last edited on
You cannot directly increase the size of a dynamically allocated array after it has been allocated (although some functions such as c realloc() gives the impression you can). If you want this then you first need to allocate a new array of the greater size, copy the elements from the original smaller array to the new larger array, delete the smaller array and then set the array pointer to the new larger array.
ayoesquire wrote:
Is it possible to write the code such that it increases the size of the dynamically allocated array by one (1) while the program is running just so that the number of elements don't exceed the maximum size that was previously allocated?

You cannot resize an array but what you can do is allocate a new larger array, copy the old values over to the new array and finally delete the old array.

That's how std::vector works, but it doesn't only allocate space for one new element each time (that would be much too inefficient), instead it usually doubles the capacity each time so that it doesn't have to do it as often.
1
2
3
4
5
6
7
8
9
10
11
E* v { new E[N]{} };  // array
E* larger { new E[N+1] }; // one larger
// copy v to larger
for (size_t i {}; i < N; ++i) {
  larger[i] = v[i];
}
larger[N] = 42; // set the additional element to something

delete[] v; // remove old array
v = larger; // make v point to the new array
++N;  // make N match the new array 


Or, as the std::vector would do it:
1
2
std::vector<E> v( N, 0 );
v.emplace_back( 42 );
or instead of the for loop:

 
std::copy_n(v, N, larger);

Unless you're learning about new/delete then if you don't want std::vector then with modern c++ you'd use dynamic memory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <memory>

using std::cout;

using E = int;

int main() {
	constexpr size_t N { 100 };
	const auto v { std::make_unique<E[]>(N)};
	size_t counter { };

	v[1] = 7; v[2] = -3; v[3] = 1;

	cout << "The array has " << N << " elements\n";
	cout << "Non-zero values stored in the array are:\n";

	for (size_t i {}; i < N; ++i)
		if (v[i]) {
			++counter;
			cout << v[i] << '\n';		// Print value of each element in the array
		}

	cout << "\nThere are " << counter << " non-zero elements\n";
}


where you don't need delete as that is automatic when v goes out of scope.
@All

Awesome! I learned so much from this interaction especially about how and why std::vector works even as it relates to the limitations of new/delete directives.

Thank you all! If y'all don't mind, I'd leave the question open for a bit (say a couple of days) before marking it as solved just in case someone else wants to chime in.

Once again, thank you all for your time and resources. Much appreciated!
Topic archived. No new replies allowed.