如何在声明后设置const char *?

时间:2012-06-02 19:07:17

标签: c++ c

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

我尝试了memcpysprintf,并将其作为“const char *”的问题

我想将“str”设置为0或1,如“v”所定义。但它必须是“const char *”

类型

2 个答案:

答案 0 :(得分:3)

我的猜测是你想在第一次声明之后更改const char的值,对吗?虽然您无法直接更改const char *的值,但您可以将指针值更改为普通变量。 例如,请在此处查看此页面:Constants in C and C++

使用指针更改const值,您可以做什么,不能做什么:(通过上面的链接):

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

这也适用于你想要的角色。

答案 1 :(得分:1)

这是与const char *的交易。它是指向const char的指针。 const char表示字符无法更改。指针不是const,所以它可以改变。

执行此操作时:

str = 48 + v;

您正在尝试将指针更改为48或49,具体取决于v。这是荒谬的。如果编译,它将指向随机内存。你想要的是改变'str'指向0或1。

因为它只能指向常量字符,所以它只能用引号指向定义为值的内容。因此,例如,它可以设置为指向“0”,这是一个常数字符或“1”,这是一个常数字符。所以你可以这样做:

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

请注意,由于str指向常量字符,因此无法修改其指向的内容:

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