0

hi, i've writen a function to get a sub array from another array

subarray(int* Array, int start,int end)
{
	typedef int* ptr;
	ptr sub;
	sub = new int[end];

	for(int i=start; i<end; i++)
	{
		int j = 0;
		Array[i]=sub[j];
		j++;
	}
	for(int l=0; l<end; l++)//added as an after thought
		cout<<sub[l] << ", ";
}

at the moment it's only showing the memory addresses rather than the variables and i can't figure out how to fix this.

any help would be greatly appreciated

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

You had some things the wrong way around:

subarray(int* Array, int start,int end)
{
	typedef int* ptr;
	ptr sub;
        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; //here, your function has no return type?
	sub = new int[count]; //now allocate "count" size.

	for(int i=start; i<end; i++)
	{
		int j = 0;
		//Array[i]=sub[j]; //this sets Array to sub, do it the other way around:
                sub[j] = Array[i];
		j++;
	}
	for(int l=0; l<count; l++)//added as an after thought
		cout<<sub[l] << ", ";
        delete[] sub; //never forget to delete, don't leave memory leaks.
}
0

You had some things the wrong way around:

thanks although it did expose a flaw in the second loop.

This topic has been dead for over six months. 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.