Function that returs char pointer behaives strange!!

This is a discussion on Function that returs char pointer behaives strange!! within the C++ Programming forums, part of the General Programming Boards category; Hi folks!!! I have a noticied a 'strange' thing when a change mine function-definition a little and I canīt understand ...

  1. #1
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    Function that returs char pointer behaives strange!!

    Hi folks!!!

    I have a noticied a 'strange' thing when a change mine function-definition a little and I canīt understand why it doesnīt work.
    I have a funtion like

    Code:
    char * test()
    {
    	char *name = "Test";
    	return name;
    }
    and this works perfectly well. But when I change it to

    Code:
    char * test()
    {
    	char name[5];
    	name[0] = 'T';
    	name[1] = 'e';
    	name[2] = 's';
    	name[3] = 't';
    	name[4] = '\0';
    	return name;
    }
    I get a warning message that "returning address of local variable or temporary". I think it has to to something that the array loses it scope or something but why is the first code-snippet working!!!!
    (Second code will give an output that is wrong).
    And also is a function that returns a pointer the same thing as a function that returns an array??
    Iīve been searching for a post that 'returns an array' but didnīt found one that solves mine problem.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >char *p = "testing";
    This is a pointer to a string literal. The string literal itself has a static storage class. You are allowed to return the pointer because this storage class allows you to do so.

    >char a[] = "testing";
    This is an array populated with a default string. The array is only available within the function it's defined, and is therefore out of scope when you return.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    okey so pointer is the right way to go. But one other problem araises then. I want to use this(name) pointer as the array in the second code-snippet.

    Code:
    char * test()
    {
    char *name;
    name[0] = 'T';
    name[1] = 'e';
    name[2] = 's';
    name[3] = 't';
    name[4] = '\0';
    return name;
    }
    I know that pointer name is uninitialized (dangerous) and this program gives 'unexpected' output. Is it possible possible to declare a pointer how 'big storage' it need so it points 'right'.

  4. #4
    Unregistered
    Guest
    in your second post the pointer name is assigned no memory. Therefore it can't be used in the manner attempted. You can assign it memory using the new operator, or equating the pointer to an array.

    version 1:

    char * name = new char[5];
    name[1] = 'T';
    name[2] = 'e';
    //etc.
    or strcpy(name, "Test");

    version 2:
    char * name;
    char array[5];
    name = array;
    *name = 'T';
    *(name + 1) = 'e';//or *(++name) = 'e';
    *(name + 2) = 's';//or *(++name) = 's';
    //etc.

    I hate pointer math so I don't use it unless I have to, which is almost never, so I could be wrong on those details.

    The problem with returning a pointer to the address of a local variable is that the local variable will go out of scope and therefore the address won't be reachable when you try to use the return value unless the memory the pointer points to is declared using dynamic memory or is static.

  5. #5
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Well your first version worked Unregistered but the second version (which is the method I would prefer) doesnīt work. This time it doesnīt even get a compiler error :-(
    Again my guess is that array goes out of scope.

    Isnīt there any other solution then using dynamic allocation??
    You mention something about static??? Is an array always static or do you have to declare it????

  6. #6
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Why not just pass the string to the function, and change it?

    Code:
    void function(char* array)
    {
         if(array){
             delete [] array;
             array = NULL;
         }
         array = new char[5];
         strcpy(array,"Test");
    }

  7. #7
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Hmm, the problem is that Iīm working on a string class and I have a function that adds two strings and return a 'concrated' string. I donīt want that the passed parameter should change.

    So far as I know I have to return a char pointer!!!!

  8. #8
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Here's how you could do it seeing that you haven't posted any code.

    Code:
    String& String::Concatenate(const char* newStr)
    {
    	char* temp;
    	
    	if(this->lpzstr!=NULL && newStr!=NULL)
    		temp = new char[strlen(newStr)+strlen(this->lpzstr)+1];
    
    	if(this->lpzstr == NULL)
    	{
    		if(newStr != NULL)
    		{
    			this->lpzstr = new char[strlen(newStr)+1];
    			strcpy(this->lpzstr,newStr);	
    		}
    		return *this;
    	}
    	if(newStr != NULL)
    	{
    		strcpy(temp,this->lpzstr);
    		strcat(temp,newStr);
    		delete [] this->lpzstr;
    		this->lpzstr = temp;
    	}
    	return *this;
    }

  9. #9
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Ops sorry, here it is.

    Code:
    String String::operator +(String &concrate)
    {
    	char *temp;
    	temp[itsLength + concrate.GetLen() +1];
    	for (int i = 0; i < itsLength; i++)
    		temp[i] = itsName[i];
    	for (i = itsLength; i < concrate.GetLen(); i++)
    		temp[i] = concrate[i-itsLength];
    	temp[itsLength + concrate.GetLen() +1] = '\0';
    	return temp;
    }

  10. #10
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Always add tests to ensure safe functionality.

    Code:
    String& String::operator +(const String& newStr)
    {
    	char* temp;
    
    	if(this->lpzstr!=NULL && newStr.lpzstr!=NULL)
    		temp = new char[strlen(newStr.lpzstr)+strlen(this->lpzstr)+1];
    
    	if(this->lpzstr == NULL)
    	{
    		if(newStr.lpzstr != NULL)
    		{
    			this->lpzstr = new char[strlen(newStr.lpzstr)+1];
    			strcpy(this->lpzstr,newStr.lpzstr);	
    		}
    		return *this;
    	}
    	if(newStr.lpzstr != NULL)
    	{
    		strcpy(temp,this->lpzstr);
    		strcat(temp,newStr.lpzstr);
    		delete [] this->lpzstr;
    		this->lpzstr = temp;
    	}
    	return *this;
    }

  11. #11
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    If Iīm not wrong it changes the object, doesnīt it???

    I would like to have a function like A = B + C, where A,B,C are strings.

    Also a 'minor' misstake in the previous code, it should be

    Code:
    String String::operator +(String &concrate)
    {
    	char *temp;
    	temp[itsLength + concrate.GetLen() +1];
    	for (int i = 0; i < itsLength; i++)
    		temp[i] = itsName[i];
    	for (i = itsLength; i < concrate.GetLen(); i++)
    		temp[i] = concrate[i-itsLength];
    	temp[itsLength + concrate.GetLen() +1] = '\0';
    	//Initiates the string with the characters found in temp
    	String tempString(temp);
    	return tempString;
    }
    Why do you use const, and why do you return a reference??
    String& String:perator +(const String& newStr)

  12. #12
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    >> If Iīm not wrong it changes the object, doesnīt it???
    It only makes the lpzstr member point to a new char*

    >>Why do you use const, and why do you return a reference??
    String& Stringerator +(const String& newStr)

    So that the function can't accidentally change the String object that was passed to it. I return a reference because...
    Do some research on operator overloading.

  13. #13
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Hmm, I do understand operator overloadning... I think we are getting away from the original post.

    In your case I only want to extract the characters newStr.lpzstr and this->lpzstr and create a char-pointer(temp) that contains newStr.lpzstr + this->lpzstr and succesfully return it.

  14. #14
    Unregistered
    Guest
    if you want string B to be concatenated onto string A but you don't want string A or string B to be changed, try this syntax:

    String & operator+(const String &) const;

    which means you don't intend to change the String passed in to the the + operator and you don't intend the + operator to change the object calling the + operator. You can also use a friend function:

    friend String & operator+(const String &, const String &)

    In both functions you declare a new String, strcpy() the char * in the first String into the new String's char * and then strcat() the second String's char * onto the new String's char * and return the new String. You have to allocate enough memory for the new String to hold both the first and second String's char *s of course. Likewise, both of these functions are likely to be used in conjuntion with an overloaded assignment operator for the String class that will allow you to do this:

    String A = "good ";
    String B = "doggie";
    String C;
    C = A + B;

  15. #15
    Unregistered
    Guest
    Code:
    String & operator+(const String B) const;
    {
       String C;
       //assuming itsname is a char * embedded in String class;
       C.itsname = new char[strlen(itsname) + strlen(B.itsname) + 1];
       strcpy(C.itsname, itsname);
       strcat(C.itsname, B.itsname);
       return C;
    }
    use whatever testing for NULL etc. that you feel important to make your program as robust as desired.

    personally I prefer the friend version as it seems easier to conceptualize, but either should work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 09:18 PM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07:54 PM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 03:25 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-30-2005, 12:21 AM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21