when you declare a string lets say
char *string;
can you give it a value? fe: gets(string)
or can you only use it as a const string like
char *string = "blabla";
when you declare a string lets say
char *string;
can you give it a value? fe: gets(string)
or can you only use it as a const string like
char *string = "blabla";
You can allocate memory using say, malloc(), and then get that pointer to point to the first character of the memory allocated. Or, you could get it to point to the first character of a character array, similiar to getting it to point to the first character of a string literal, except that you would be able to modify the contents of the array through the pointer.
Oh, and do not use gets() even if you were working with a character array.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
yeah i used gets for a quick example
i also thought you were able to declare a string like char *conststring; and then give it a value via gets() or fgets() or what ever, but you just werent able to change it with lets say *(conststring + i) = 'a'... Guess I was wrong or am I missing something?
What you are missing is that the pointer needs to point to something. Functions like gets and fgets write to what the pointer points to, thus you cannot just pass the pointer to them when it is a null pointer or does not point to anything valid.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I get what you mean laserlight, you are right.
But isn't there a way to give a value to a char pointer that isn't pointing to anything? I really thought there was a possibility to do this? Just declare char *string; and give a const string to it that you cannot alter. Did i really dream this lol
Yes, and I listed two: dynamic memory allocation and setting it to point to the first character (or somewhere else) of a character array. Getting it to point to the first character of a string literal is a third way, but not very relevant for what you intend to do.Originally Posted by boxden
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
yes i know but i mean without allocating. But I guess not than thank you
I think you're thinking of
foo now points to a legitimate memory address, but that memory address is read-only (and so foo should really be a "const char *" instead).Code:char *foo = "const string";
(EDIT: And re-reading the thread, that's where we started, isn't it? So yes, there's nothing else.)
Last edited by tabstop; 04-17-2010 at 05:33 PM.
Well... how do you store cookies in a jar when you don't have a jar and cannot obtain one?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)