Skip to main content
GameDev.net gamedev.net
🔒 Locked

pointers to strings

Started by djurens Sep 9, 2003 at 7:13 PM 4 replies 350+ views
Original Post
djurens
djurens
class char *pText ... function (char *txt) { pText=txt; is this a safe way to store "" string data? txt exists only within the function, and pText is a pointer to an adress. Does this mean that the string which pText points to can be overwritten if unlucky, or is the space reserved permanently after the pointer pText is assigned to the string data? Thanks in advance Mattias
Mathematix
Mathematix
It means that you are making pText point to txt.

[edited by - mathematix on September 9, 2003 8:18:07 PM]
Sneftel
Sneftel
It really depends on what you''re passing into function as txt. If txt points to a string constant, of course, you''re safe. If txt points to a char array that is local to the function that function is called from, you are very not-safe. If txt points to dynamically allocated memory, you''re safe up until your program calls delete or free on txt.


How appropriate. You fight like a cow.
djurens
djurens
so if i call the function with : ->function("abcd") then i am safe, right?

but i am worried with what you said about locals, if i call the function from my maingame (object) function : ->function(*pString) and pString is :

char pString;
pString="abcd"

if it safe then as long as pString is alive?
zipiicool
zipiicool
If you want to save the string that one string pointer is pointing to, to another string pointer, use the strdup() function.

example:

char* pString = "Hello";
char* pCopyTo = "";
pCopyTo = strdup(pString);

or in a class:

class CStr
{
char* pStr;
void CpyStr( char* Copy ){ pStr = strdup(Copy); }
};



this copies the memory that one pointer points to to another pointer. Tis is useful when dealing with dealing with things like user input, where things like character arrays might overflow.

This method is safe when copying strings defined in functions that are deleted in functions, as well as global ones. I had this same string issue, my strings were becoming invalid after the function had ended, and string pointers were just pointing to arrays or other pointer''s memory.
ZZZzzz......
djurens
djurens
ok, thanx a lot!!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.