首先,请找出一种可以使用的方法std::string
。如果你继续你选择的路径,你肯定会创建错误的程序。
话虽如此,这是您的答案:您如何声明x
以及如何分配它,在很大程度上取决于您以后如何使用它。这是一个例子:
#include <stdio.h>
int main(int ac, char **av) {
const char* x;
switch(ac) {
case 0:
x = "0";
break;
case 1:
x = "1";
break;
default:
x = "DANGER!";
break;
}
printf("%s\n", x);
return 0;
}
In this first example, we set the pointer x
to point to one of three possible const char arrays. We can read from those arrays later (as in the printf
call), but we can never write to those arrays.
Alternatively, if you wish to create an array you can later write to:
#include <stdio.h>
#include <string.h>
int main(int ac, char **av) {
char x[32]; // make sure this array is big enough!
switch(ac) {
case 0:
strcpy(x, "0");
break;
case 1:
strcpy(x, "1");
break;
default:
strcpy(x, "NOT 0 nor 1:");
break;
}
strcat(x, ", see?");
printf("%s\n", x);
return 0;
}
EDIT: Get rid of incorrect const
from 2nd example.