Thread: char* ???

  1. #1
    Unregistered
    Guest

    Unhappy char* ???

    Why doesn't that work ??? ... (the red term)
    Code:
    { ...
    int ierg = <s.th.>;
    char *zkerg;
    
    zkerg = itoc(ierg);
    ... }
    ... and itoc is defined :
    Code:
    char* itoc(int zahl)
    {
    	char *temp;
    
    	_itoa(zahl, temp, 10);
    	
    	return temp;		
    }

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You'll have to allocate memory, either on the stack or heap, to store the string pointed to by char *temp. If you use stack memory then it will go out of scope if it's created in the function and this function returns (you wont be able to access it after the function's returned).
    zen

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    1
    OK!

    So far so good ... now i wrote
    Code:
    char *temp = new char;
    _itoa(zahl, temp, 10);
    return temp;
    but when should i delete temp ?
    after return ?

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    You should call delete before the return to the main function. As the *temp is a local variable, it will be out of scope after the return and you will not be able to release the memory

  5. #5
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You may have to allocate more room if the number you're converting is longer than one digit and need include space for the terminating NULL, eg. for 111 you'd need to do char *temp = new char[4]. It may be easier just to use an array on he stack and pass it into the function -

    char temp[10];
    int number = 123;
    //You'd have to change the prototype of itoc to take a char* as
    //a parameter.
    itoc(number,temp);

    Then you wouldn't have to allocate or deallocate the memory.
    zen

Popular pages Recent additions subscribe to a feed