C ++将int分配给char *数组

时间:2020-02-17 21:15:01

标签: c++ arrays

很抱歉,是否曾经有人问过这个问题,但是我找不到任何有助于我的情况的东西。 我正在尝试为char数组中的索引分配一个整数。在这种情况下,将33分配给令牌数组的索引。

char token[100];
int num = 33;
//Assigning num to this place in array
token[1] = num; //How do I make this work?

我希望33是令牌数组中的索引,但是当我分配它并打印出来时,它给了我'!',这是33的ASCII值。我想将num转换为字符串,然后将其分配给索引。那么,如何将num转换为字符串,然后将其分配给令牌数组?

1 个答案:

答案 0 :(得分:1)

如果您的意思是,您有一个指向char数组的指针,则可以执行此操作。

char* token = new char[100];
    token[0] = 33; // You actually get '!' since char 33 is indeed '!'
std::cout << (int)token[0] << std::endl; // cast it to an int, 33 is back

如果要使用char指针数组,可以执行以下操作:

char* token[100];
char* temp = new char; // You need a char* to store it since char is 1byte and int is 4byte
    *temp = 33; // or *temp = num; in your case
    token[0] = temp; // You still get '!' since char 33 is indeed '!'
std::cout << (int)*token[0] << std::endl; // cast it to an int