将常量字符* 转换为字符时出错
error converting const char* to char
我正在尝试将一个字符变量转换为一个常量字符变量,但我有以下错误.变量字符的内容还可以,在这种情况下是"H"和"e",但是当我转换为常量字符*时,我后面有字母+其他东西。你们能告诉我我哪里做错了什么吗?
请看链接中的图片!
#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
在此处输入图像描述
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。
问题是您没有以空字符(