将常量字符* 转换为字符时出错

error converting const char* to char

本文关键字:字符 出错 常量 转换      更新时间:2023-10-16

我正在尝试将一个字符变量转换为一个常量字符变量,但我有以下错误.变量字符的内容还可以,在这种情况下是"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。

问题是您没有以空字符((终止Body(。第二个问题是你的循环,你试图访问超出范围的东西。代码应该是这样的:

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

在 c/c++ 语言中,任何原始字符串的末尾都需要 null char,因为这有助于它理解字符串的结尾。

问题是您正在访问 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 尝试打印所有内容,直到遇到空,以防您传递它 const char *

所以

std::cout << "Const char : " << *Line2;