c++ pointers beginner

Hi, I'm new to c++/pointers, I'm having a little hard time with them

I'm using VS2010(clr project) compiler, it may be irrelevant.

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
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>

using namespace System;
using namespace std;

void newArr(int **,int *,int);
void printArr(int *,int);

int main(array<System::String ^> ^args)
{
	int *test;
	int i=0;
	newArr(&test,&i,1);
	printArr(test,i);

	system("pause");
	return 0;
}

void newArr(int **vect,int *size,int num){
	int *neo=new (nothrow) int[*size+1];
	 for (int i = 0; i < *size; i++)
	{
		neo[i] = *vect[i];
	}
	neo[*size]=num;
	*size=*size+1;
	//delete [] vect;
	*vect=neo;
}


void printArr(int *vect,int size){
	for(int i=0;i<size;i++){
		cout<<vect[i]<<" "; 
	}
	cout<<endl;
}


My question is why I can't(or shouldn't) put the commented part in newArr.

How may I free that memory space once I add a new number?

I thank your help in advance
Last edited on
This looks like some kind of MS C# or managed C++ or .NET type language; not plain C++.

That said, assuming the rules for delete are the same, you can only delete memory that was allocated using new. Given that vect was not allocated using new, you can't use delete on it (the first time round, what exactly would you be deleteing?). vect isn't even a pointer to an array - it's a pointer to a pointer.

Why are you passing a pointer to a pointer? This doesn't make a lot of sense in the context of what you're trying to do.
Last edited on
Thanks for the answer: I'm trying to reallocate vect, is it better to do it this way?

1
2
3
4
5
6
7
8
9
10
void newArr(int *&vect,int *size,int num){
	int *neo=new (nothrow) int[*size+1];
	 for (int i = 0; i < *size; i++)
	{
		neo[i] = vect[i];
	}
	neo[*size]=num;
	*size=*size+1;
	vect=neo;
}



Also, shouldn't I free the previously allocated space?

Thanks for your help once again
Last edited on
Also, shouldn't I free the previously allocated space?

Only if it was allocated using malloc or new. In your code, the very first time you call newArr, it hasn't been.
Is that method newArr can works for resize dynamic array?
Topic archived. No new replies allowed.