Question:
C/C++ pointers as strings?
2008-04-14 15:53:43 UTC
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 >> string;

instead of:

char *string = new char[100];
std::cin >> 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...
Four answers:
C B
2008-04-14 16:54:31 UTC
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.
iqbal
2008-04-14 21:22:05 UTC
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.
2008-04-14 16:03:04 UTC
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 >> string;



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



#include



string mystring;

std::cin >> mystring;

std::cout << mystring;
blidge
2017-01-05 22:27:25 UTC
printf("szName is saved at %dn", &szName); you're employing %d.. which you're telling the compiler to print out a decimal. printf("szName is saved at %sn", &szName); ... something like this would paintings (undecided if s is the impressive one, yet attempt to make certain which letter denotes a string whether that's not 's')


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...