Pointer Paranoia

Goals:
(1) Pass an array to a function and create a new array twice the size of the argument array.
(2) Copy the contents of the argument array to the new array and initialize the unused elements of the second array to 0.
(3) The function returns a pointer to the new array.

I am paranoid to keep debugging as I get the error message:
Debug Assertion Failed!

And do not want to start messing up things in my computer.. Please help me point out what is wrong with my function..

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
#include <iostream>
#include <string>
using namespace std;

// Function prototype
int* myFunc(int [], int);

int main()
{
	// Create first array
	const int SIZE=5;
	int arr[SIZE]={4,4,0,1,7};
	// Function call, pass array
	myFunc(arr, SIZE);
	delete [] arr;
	system("Pause");
	return 0;
}

int* myFunc(int a1[], int SIZE)
{
	int* a2=new int[SIZE*2];
	for(int count=0;count<SIZE;count++)
	{
		a2[count]=a1[count];
	}
	return a2;
}


C++ masters.. Please help..
Debug Assertion Failed!

That isn't going to make your machine blow up or anything like that.

The issue (i think), is you are calling delete (on line 15) on an array you don't have to call delete on :) 'arr' has been created on the stack.

The array you ARE dynamically creating is the one on line 22.

The function returns a pointer to the new array.

Even though you are declaring and defining a function to do this, you aren't actually doing anything in main() with the return value on line 14.

You are nearly there though.
Last edited on
In addition to what mutexe said, you still have to write the code to initialize the bottom half of a2 to 0.
Topic archived. No new replies allowed.