C++ new keyword question

Prozix

New Member
Reaction score
7
Hello,

I am confused.

I've made two functions:
Code:
void Test1(int * i){
        i = new int;
        *i = 1;
}

int * Test2(){
	int * i = new int;
	*i = 1;
	return i;
}

now here's how I tried to use them:

Code:
int main(){
	int * i;
	Test1(i);
	cout<<*i<<endl; //big fat runtime error
}
int main(){
	int * i = Test2();
	cout<<*i<<endl; //good
}
int main(){
	int * i;
	{
		i = new int;
		*i = 1;
	}
	cout<<*i<<endl; //works too but it's the same as the first try when you completely inline Test1(i);
}
I haven't got a clue why my program crashes. I'm really really sad:(
 

phyrex1an

Staff Member and irregular helper
Reaction score
447
Try think about it. Would this program work?

Code:
void Test1(int  i){
        i = 1;
}

int main(){
	int i;
	Test1(i);
	cout<<i<<endl; 
}

Why not? Because variables are passed by value, not reference. So, how do we solve it? By passing a pointer to i instead.

Now, take a look at your program. It's conceptually the same as my flawed example above (except that you do some pointer stuff to).
I think the correct code would be this:
Code:
void Test1(int ** i){
        *i = new int;
        **i = 1;
}
int main(){
	int *i;
	Test1(&i);
	cout<<*i<<endl; //hopefully not a big fat runtime error
}
From this you should be able to understand why your last main works ^^
Remember that it is up to you to destroy stuff you create with new.
 

Prozix

New Member
Reaction score
7
Now that, makes a lot of sense ^^. Thanks for you fast reply.

Code:
struct str{
	char * m_s;
};
void NewStr(str * s, uint size){
	s->m_s = new char[size];
}
int main(){
        str nStr;
        NewStr(&nStr);
}
It becomes both more and less confusing when I write it down like this :banghead:

are the comments right?
Code:
void Test1(int ** i){ //pointer to an int pointer
        *i = new int; //value of the pointer is the adress of a new int
        **i = 1; //value of the address the pointer points to is 1
}

int main(){
	int * i;//declare a pointer to an int type variable
	Test1(&i);//address of the pointer as a parameter
	cout<<*i<<endl; //Hurray!
        delete i; //free the allocated memory
        i = NULL; //null the pointer
        return 0;
}
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top