我正在尝试将一个char变量转换为const char变量,但是出现以下错误。 char的内容可以,在这种情况下为“ H”和“ e”,但是当我转换为const char *时,后面会有字母+其他东西。你们能告诉我我在哪里做错了吗?
请通过链接查看图片!
#include <iostream>
#include <Windows.h>
#include <lmcons.h>
#include <stdio.h>
#include <stdlib.h>
char Body[] = { 'H', 'e', 'l', 'l', 'o' }; // elements of char array
int size = sizeof(Body); // get size of Body array
char Line;
std::cout << "Size : " << size << "\n"; // view the size of Body array
for(int i=0; i<=size; i++) // for statement : from first element to the last element of array
{ // beginning of for statement
Line = Body[i]; // get each element from Body array and put to char variable
std::cout << "Char : " << Line << "\n"; // view the content of char variable
const char *Line2 = &Line ; // convert from from char to const char*
std::cout << "Const char : " << Line2 << "\n"; // view the content of const char* variable
} // end of for statement
答案 0 :(得分:2)
const char *Line2 = &Line ;
不会从角色中神奇地创建一个字符串;因为字符串必须以Null(或0)结尾,所以您不能将此指针传递给cout,因为它希望处理多个字符。如果您将其更改为
char Line[2] = {0}; // 0 initialise all the chars
Line[0] = Body[i];
Line[1] = 0; // completely not required, but just making the point
char* Line2 = &Line[0]; // there are other cleaner ways, but this shows explicitly what is happening
std::cout << Line2;
您没有UB。
答案 1 :(得分:1)
问题是,当您以如下方式运行循环时,您正在访问Body [5]
for(int t=0;t<=sizeof(Body);t++){}
如果您删除那个=号,那没关系。
for(int t=0;t<sizeof(Body);t++){}
还尝试转换
std::const char *Line2 = const_cast<const char *>(&Line );
使用std::const_cast<>()
将非常量转换为常量数据类型。
如果要直接从控制台删除那些多余的东西,还需要取消引用const char *。 std :: cout尝试打印所有内容,直到遇到null为止(如果您将其传递给const char *
所以
std::cout << "Const char : " << *Line2;
答案 2 :(得分:1)
问题是您没有用空字符(Body
)终止\0
。第二个问题是您试图访问超出范围的循环。代码应如下所示:
char Body[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; // elements of char array
int size = sizeof(Body); // get size of Body array
char Line;
std::cout << "Size : " << size << "\n"; // view the size of Body array
for(int i=0; i<size; i++) // for statement : from first element to the last element of array
{ // beginning of for statement
Line = Body[i]; // get each element from Body array and put to char variable
std::cout << "Char : " << Line << "\n"; // view the content of char variable
const char *Line2 = &Line ; // convert from from char to const char*
std::cout << "Const char : " << Line2 << "\n"; // view the content of const char* variable
} // end of for statement
在c / c ++语言中,任何原始字符串的末尾都需要null char,因为这有助于它理解字符串的结尾。