is there a better way of allocating number of elment on an array

#include <iostream>

using namespace std;

int main()
{
int elm = 0;
int size = 0;
int *array;


array = new int [size];
// the array starts at array[1] with value 1
// the array ends at array[5] with value 5
for(int count=0; count<=5; count++)
{
array[elm]= count;
elm+=1; size +=1;

delete [] array;

}
// this prints the array
for(int new_count=1; new_count <=5; new_count++ )
cout<<"The array is: "<<array[new_count]<<endl;

cin.get();
return 0;
}
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 namespace std;

int main()
{
	int elm = 0;
	int size = 0;
	int *array;


	array = new int [size];

	// the array starts at array[1] with value 1
	// the array ends at array[5] with value 5
	for(int count=0; count<=5; count++)
	{
		array[elm]= count;
		elm+=1; size +=1;

		delete [] array;
	}

	// this prints the array
	for(int new_count=1; new_count <=5; new_count++ )
	cout<<"The array is: "<<array[new_count]<<endl;

	cin.get();
	return 0;
}
line 8: why is size=0 if you want to save 5 elements in your array?
line 19: why do you increase size, it doesn't get used anymore
line 21: you know that you delete the dynamic array, before the loop is done, right?
lines24-end: since the array is already deleted, there is nothing to print


i'd just use "{1,2,3,4,5}" to set up the array
Line 8: its an n number of array so it does not matter how big it is i should have stated with 1
Line 19:because cause u dont know how many elements youll need could be 10 could be 1000
Line 21: this is the meat and bones the code works but im uneasy about this line maybe i could put it on another loop outside this one.
Line 24: it prints

Cause you dont know what the input is. it wont be necessarily be 1 to 5 array[elm] = all prime number in the world. Or array[elm]= fibanocci
- if you delete the array before the entire loop runs, then you won't be able to use it anymore.

- Thus, you cant cout any value in it.
Line 8: its an n number of array so it does not matter how big it is i should have stated with 1

There is no such thing as an "n number of array." What you have is an array of 0 elements.


Line 19:because cause u dont know how many elements youll need could be 10 could be 1000

Increasing size does not increase the capacity of the array.


Line 21: this is the meat and bones the code works but im uneasy about this line maybe i could put it on another loop outside this one.

This results in undefined behavior as you feed the same memory address to delete 6 times. And of course, line 18 is also incorrect, since your array has no elements.

Line 24: it prints

Your array has no elements so there is nothing to print. Besides that, array indices begin at 0, not 1.

Its n number of element i should say not n number of array.
Topic archived. No new replies allowed.