简体   繁体   English

创建临时字符*并进行打印的正确方法是什么?

[英]What is the proper way to create a temporary char* and print to it?

I have a helper function that takes an unsigned char array of a fixed length, and returns it as a formatted char *. 我有一个辅助函数,该函数采用固定长度的无符号char数组,并将其作为格式化的char *返回。 However, I'm having some problems. 但是,我遇到了一些问题。

I tried 我试过了

char* byteArrayToString(unsigned char byte[6]) {
    char t[18] = {""};
    char* str = t;
    sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
    return str;
}

and

char* byteArrayToString(unsigned char byte[6]) {
    std::string t = "";
    char* str = t;
    sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
    return str;
}

and

char* byteArrayToString(unsigned char byte[6]) {
    char* str = new char();
    sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
    return str;
}

The second one results in some side effects of the value of that string being changed. 第二个导致更改该字符串的值的某些副作用。 The first one ends up giving me junk values and the last seg faults (but I can't figure out why). 第一个最终给了我垃圾值,最后一个给了段错误(但我不知道为什么)。

Proper way is to return std::string as: 正确的方法是将std::string返回为:

#include <sstream>   //for std::ostringstream
#include <string>    //for std::string
#include <iomanip>   //for std::setw, std::setfill

std::string byteArrayToString(unsigned char byte[6]) 
{
    std::ostringstream ss;
    for(size_t i = 0 ; i < 5 ; ++i)
         ss << "0X" << std::hex << std::setw(2) << std::setfill('0') << (int) byte[i] << ":";
    ss << "0X" << std::hex << std::setw(2) << std::setfill('0') << (int) byte[5];
    return ss.str();
}

Online demo 在线演示

On the callsite you can get const char* as: 在呼叫站点上,您可以获取const char*为:

std::string s = byteArrayToString(bytes);
const char *str = s.c_str();

The problem with your first one is not in the printing, but in the returning. 您的第一个问题不在打印中,而在返回中。 You're returning a pointer to an array which has been reclaimed (because it is an automatic variable, its lifetime ends when the function returns). 您将返回指向已回收的数组的指针(因为它是一个自动变量,所以函数的返回将终止其生命周期)。

Instead try: 而是尝试:

string byteArrayToString(const unsigned char* const byte)
{
    char t[18] = {""};
    sprintf(t, "%02X:%02X:%02X:%02X:%02X:%02X", byte[0], byte[1], byte[2], byte[3], byte[4], byte[5]);
    return t;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM