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

「const char *」であるという問題を試しmemcpyてみましたsprintf

「v」で定義されているように、「str」を0または1に設定したい。ただし、「 const char* 」型でなければなりません

4

2 に答える 2

4

私の推測では、最初に宣言した後に const char の値を変更したいと思いますよね?const char* の値を直接変更することはできませんが、ポインター値を通常の変数に変更できる場合があります。たとえば、このページを見てください: C および 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

これは、あなたがやろうとしているような文字でも機能します。

于 2012-06-02T19:14:46.863 に答える
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.  
于 2012-06-02T19:23:04.020 に答える