为什么当调用另一个函数时,这个字符数组的值会发生变化

Why is this array of chars changing value when another function is called?

本文关键字:数组 变化 字符 另一个 调用 函数 为什么      更新时间:2023-10-16

为什么我的comportstr在这段代码中被更改为垃圾值?我不明白如果我的char数组没有任何改变,它怎么会改变值。这两份打印报表之间没有其他内容。

int main(int argc, char* argv[])
{  
    char comportstr[10];
    sprintf(comportstr,"COM%d",COMPORT_NUM);
    if(DEBUGGING) fprintf(stderr,"str is: %sn", comportstr); //prints str is: COM3
    sprintf(curtime , "%s" , currentDateTime());
    if(DEBUGGING) fprintf(stderr,"str is: %sn", comportstr); //prints str is: ;32
}

以下是currentDateTime的作用。它根本不会修改comportstr。

// Gets current date/time, format is YYYY-MM-DD.HH;mm;ss
const std::string currentDateTime() 
{
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit http://www.cplusplus.com/reference/clibrary/ctime/strftime/
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%H;%M;%S", &tstruct);
    return buf;
}

currentDateTime()函数中,您将返回一个传递给sprintf()的vararg接口的std::string。这不起作用,因为您无法将标准布局类型传递给vararg接口。也就是说,对sprintf()的第二次调用会导致未定义的行为。

你可以通过使用来避免这个问题

sprintf(curtime , "%s" , currentDateTime().c_str());

或者,实际上,

strcpy(curtime, currentDateTime().c_str());
sprintf(curtime , "%s" , currentDateTime());

currentDateTime函数返回一个std::string,但%s仅用于C样式字符串。您需要currentDateTime().c_str()。你的编译器应该给你一个警告。