Pointers

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int *minuscontent(int *, int);
int *randomize(int *, int);

int main()
{
	const int size = 5;
	int array[size];
	int *mptr, *cptr;

	mptr = randomize(array, size);
	for (int i = 0; i < size; i++)
		array[i] = mptr[i];
	cptr = minuscontent(array, size);

	for (int i = 0; i < size; i++)
		cout << mptr[i] << " ";
	cout << endl;

	for (int i = 0; i < size; i++)
		cout << cptr[i] << " ";
	cout << endl;

	delete[] mptr;
	delete[] cptr; mptr = 0; cptr = 0;

	system("PAUSE");
	return 0;
}
int *randomize(int *ptr, int capacity)
{
	ptr =  new int[capacity];
	srand(time(0));
	for (int i = 0; i < capacity; i++)
		ptr[i] = 1 + rand() % 101;
	return ptr;
}
int *minuscontent(int *ptr2, int capacity)
{
	for (int i = 0; i < capacity; i++)
	{
		ptr2[i] -= 1;
	}
	return ptr2;
}


Anything fishy in this code, when I compile it it works correctly but Visual Studio gives me an error.
Anything fishy in this code,

Yes. You call delete on the same memory twice, resulting in undefined behavior.

There are two deletes in your program and only one new. You do the math. ;)
Do i delete the ptr in which is local, or the mptr in the main program? I know I should remove the delete cptr one.
Presumably, you meant for the array allocated in randomize to make it back to main, so ownership of the memory logically belongs in the caller. delete it there when you're finished using it.
on line 18 you make cptr point to array, which is not dynamically allocated. Don't delete cptr.
Last edited on
Okay, thank you very much guys.
Topic archived. No new replies allowed.