jdl
jdl

Reputation: 6323

How do I set a const char* after declaration?

//v is a random number 0 or 1
const char *str;
//str = 48 + v; //how to set??  

I tried memcpy and sprintf and get issues with it being "const char*"

I want to set "str" to 0 or 1 as defined by "v". But it must be of type " const char* "

Upvotes: 2

Views: 7412

Answers (2)

user1342784
user1342784

Reputation:

Here's the deal with const char *. It is a pointer to const char. const char means that the characters cannot change. The pointer is not const, so it can change.

When you do this:

str = 48 + v;

You are attempting to change a pointer to either 48 or 49, depending on what v is. This is nonsensical. If it compiled, it would point to random memory. What you want is to change what `str' points to to 0 or 1.

Since it can only point to constant characters, it can only point to something defined as a value, in quotes. So, for example, it can be set to point to "0", which is a constant character or "1", which is a constant character. So you can do something like this:

str = "0"; // point to a constant character string "0"
if( v )
    str = "1"; // point to a constant character string "1"

Note that since str points to constant characters, you cannot modify what it points to:

*str = '1'; // Won't work because you are trying to modify "0" directly.  

Upvotes: 1

Rivasa
Rivasa

Reputation: 6740

My guess is you want to change the value of the const char after you first declare it, correct? While you cannot change the value of the const char* directly, you may be able to change the pointer value to a normal variable. For example look at this page here: Constants in C and C++

This is what you can and cannot do using your pointers to change const values: (Adopted from link above):

const int x;      // constant int
x = 2;            // illegal - can't modify x

const int* pX;    // changeable pointer to constant int
*pX = 3;          // illegal -  can't use pX to modify an int
pX = &someOtherIntVar;      // legal - pX can point somewhere else

int* const pY;              // constant pointer to changeable int
*pY = 4;                    // legal - can use pY to modify an int
pY = &someOtherIntVar;      // illegal - can't make pY point anywhere else

const int* const pZ;        // const pointer to const int
*pZ = 5;                    // illegal - can't use pZ to modify an int
pZ = &someOtherIntVar;      // illegal - can't make pZ point anywhere else

This also works for chars like you're trying to do.

Upvotes: 5

Related Questions