0

i keep having a problem with my arrays.

when i set them up and try to re-use them elsewhere i only get the last part of the array and all the rest are pointers.

typedef int* ptr;
ptr sub;//dynamic

int count = end - start; //the sub-array's size is not "end", but "end - start".
if (count <= 0) //check that you actually have a sub-array to create.
	return 0; //here, your function has no return type?
sub = new int[count];
	
for(int i=start; i<end; i++)
{
	int j = 0;
	sub[j] = Array[i];
	cout<<sub[j]<<", ";
	j++;
}
for(int l=0; l<count; l++)
{
	cout<<sub[l] << ", ";
}
delete sub;

can someone help me with this please.

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by dflatt
0

Line 11. Move this declaration elsewhere. This declaration makes the variable j local to the statement block that the for loop executes, which isn't a bad idea, but it doesn't work the way you think. At the end of each iteration of your for loop, the integer variable j is destroyed and recreated and re-initialized as 0 at the start of each iteration. This results in every Array being stored to sub[0] instead of the relevant element of the "sub-array".

Another option is to declare j "static". This will give it a "permanent" value that persists from one iteration to the next.

Edited by Fbody: n/a

0

Line 11. Move this declaration elsewhere. This declaration makes the variable j local to the statement block that the for loop executes, which isn't a bad idea, but it doesn't work the way you think. At the end of each iteration of your for loop, the integer variable j is destroyed and recreated and re-initialized as 0 at the start of each iteration. This results in every Array being stored to sub[0] instead of the relevant element of the "sub-array".

Another option is to declare j "static". This will give it a "permanent" value that persists from one iteration to the next.

thanks man

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.