C++ Question

Discussion about everything. New games, 3d math, development tips...
Post Reply
Alpha Omega
Posts: 288
Joined: Wed Oct 29, 2008 12:07 pm

C++ Question

Post by Alpha Omega »

Hello why doesn't this code work?

Code: Select all

#include <iostream>
 
using namespace std;
 
void test(char* pointer)
{
    pointer = new char[20];
}
 
int main()
{
 
    char * pointer =0;
    test(pointer);
    pointer[0] ='!';
    pointer[1] = 'H';
    pointer[2] = 'E';
    pointer[3] = 'L';
    pointer[4] = 'L';
    pointer[5] = 'O';
    pointer[6] = ' ';
    pointer[7] = 'W';
    pointer[8] = 'O';
    pointer[9] = 'R';
    pointer[10] = 'L';
    pointer[11] = 'D';
    pointer[12] = '!';
 
    cout << pointer << endl;
    
    delete [] pointer;
    return 0;
}
 
I always thought that new would allocate the memory until you called delete [] pointer; but when the function exits, does the function implicitly call delete[] or does new have a scope I didn't know about?

*edit2 typo*
CuteAlien
Admin
Posts: 9930
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: C++ Question

Post by CuteAlien »

Those variables have the same name, but they are not on the same address. You have 2 places in memory which you can access by using the name "pointer" in your code. One is only valid within test and you write into it the address of some block of memory you allocated. As soon as the function is left that memory is still allocated but the place in memory where you wrote it's address down is no longer accessible.

What you want is either a pointer to a pointer or a reference to a pointer.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Alpha Omega
Posts: 288
Joined: Wed Oct 29, 2008 12:07 pm

Re: C++ Question

Post by Alpha Omega »

Yes I see it now. They would say you are passing the address by value and therefore doesn't alter the original variable. Thanks.
Post Reply