Thursday, July 9, 2009

C/C++ pointers as strings?

I am a relative novice at C++, and I am trying to write a stack class that holds lines of text. I need to hold everything in pointers because I don't know the sizes of things, and I have one question. Do you have to use new or malloc to allocate adequate memory to a pointer, or will it act intelligently? For example will:





char *string = new char;


std::cin %26gt;%26gt; string;





instead of:





char *string = new char[100];


std::cin %26gt;%26gt; string;





possibly cause it to segfault or corrupt other variables (I know it will at least hold the data)? I haven't had that happen before, but just to make sure...

C/C++ pointers as strings?
the above answer is excellent advice (or below, the guy who said use strings). Do NOT use arrays of chars. You risk buffer overflow and if that happens your program will be entirely compromised. A buffer overflow in your case would be when you had a char array of say 100, but the user entered a line of text with over 100 chars. After 100, you're program will be writing char values to memory that is outside of your array and could be other variables, return values, etc.
Reply:Hi,


If u r using char pointers then dont worry about the size of string, to be saved in that char pointer.





Poiter reuires 2 bytes only. Char pointer holds only the address of the string not the string itself.





so


char *p;


p="a";


or


p="abcdefghijklmnopqrstuvwxyz";





so either u save a character or a string of any length, doesnt matter.
Reply:These examples do not make sense to me. 'char' is a primitive type and not a class.





This is how I would declare string. It is a simple array of char big enough for what you will use it for.





char string[100];


std::cin %26gt;%26gt; string;





If you use the C++ string class then it will resize and do clever things automatically. Hurrah!





#include %26lt;string%26gt;





string mystring;


std::cin %26gt;%26gt; mystring;


std::cout %26lt;%26lt; mystring;


No comments:

Post a Comment