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

Recommended Answers

All 2 Replies

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.
}

You had some things the wrong way around:

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.