//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* 」型でなければなりません
私の推測では、最初に宣言した後に 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
これは、あなたがやろうとしているような文字でも機能します。
との取引はこちら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.