c++ - 将 char 数组连接在一起

标签 c++ concatenation strcpy strncpy

这是几年前我认为微不足道的事情......自从我涉足 C 或 C++ 以来已经有一段时间了,我遇到了一个现在导致偏头痛的问题。

我收到以下代码的错误消息:

CompressFile::CompressFile(wchar_t *WorkingDirectory, wchar_t *File)
{
    int bzipError = BZ_OK;

    wprintf(L"Attempting to compress %s%s\n", WorkingDirectory, File);

    wchar_t FileRawInput[MAX_PATH];
    wcsncpy(FileRawInput, WorkingDirectory, sizeof(FileRawInput));
    wcsncat(FileRawInput, File, sizeof(FileRawInput));

    wchar_t bzipCompressedOutput[MAX_PATH];
    wcsncpy(bzipCompressedOutput, FileRawInput, sizeof(bzipCompressedOutput));
    wcscat(bzipCompressedOutput, L".bz2"); 

    wprintf(L"Output of string bzip: %s\n", bzipCompressedOutput);
    wprintf(L"Output of string raw: %s\n", FileRawInput);
}

我在第 8 行收到以下错误:

Unhandled exception at 0x64F4C6D1 in ias-agent.exe: 0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003).

我已经竭尽全力避免使用 string 类,我想暂时保持这种状态。我想要做的就是将两个字符串加在一起用于 RawFileInput 然后将 RawFileInput 的值添加到 bzipCompressionOutput 最后,连接 .bz2bzipCompressionOutput 的末尾。

最佳答案

last page of chapter 4 in his book :“C++ 编程语言”Bjarne Stroustrup the creator of C++说:

Prefer strings over C-style strings

这只是建议,但我鼓励您遵循它。


但你真正的问题是你正在占用内存 not sizeof(FileRawInput) wchar_t 在你的 FileRawInput 同样bzipCompressedOutput数组中没有sizeof(bzipCompressedOutput),有MAX_PATHwchar_t两个都。问题是 sizeof 会告诉你数组中的字节数,但如果每个元素都大于 1 个字节,那么你就错误地告诉了 wcsncpywscncat 你的字数。 wchar_t 一般为 2 个字节:https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx这意味着您有效地调用了 wcsncpy(FileRawInput, WorkingDirectory, 200)。在您分配的内存之外占用内存 100 wchar_t。更正此问题将消除您的段错误。

但为了打印宽字符串,您需要正确使用 %ls 修饰符来 wprintf

最终您的代码应如下所示:

wprintf(L"Attempting to compress %ls%ls\n", WorkingDirectory, File);

wchar_t FileRawInput[MAX_PATH];
wcsncpy(FileRawInput, WorkingDirectory, MAX_PATH);
wcsncat(FileRawInput, File, MAX_PATH);

wchar_t bzipCompressedOutput[MAX_PATH];
wcsncpy(bzipCompressedOutput, FileRawInput, MAX_PATH);
wcscat(bzipCompressedOutput, L".bz2");

wprintf(L"Output of string bzip: %ls\n", bzipCompressedOutput);
wprintf(L"Output of string raw: %ls\n", FileRawInput);

Live Example

编辑:

OP 已默认 Bjarne Stroustrup 的建议并转至 wstring:Concatenating char arrays together但是对于仍然坚持使用这些 C 风格函数的其他人来说,MAX_PATH 必须足够大以容纳 wsclen(WorkingDirectory) + wsclen(File) + wsclen(L".bz2") 加上 L'\0' 字符,因此在此函数上放置一个 if 语句可能会有用,或者可能:

assert(MAX_PATH > wsclen(WorkingDirectory) + wsclen(File) + wsclen(L".bz2"))

关于c++ - 将 char 数组连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37439171/

相关文章:

c - strcpy给出段错误

c++ - 为什么我的代码中会出现 strcpy 运行时错误?

c++ - 关于 std::vector 的两个简短问题

c++ - 在空格处拆分字符串并返回 C++ 中的第一个元素

c++ - 如何让我的 OpenGL 相机旋转 360 度

python - 附加两个 csv 文件时如何修复 pandas concat

c++ - 允许用户在内部实现链表时与 std::strings 交互?

c# - 将所有 String 元素从 List 连接到 String 的最快方法

java - java中通过字符串连接生成查询——变量值不被替换

c - 警告 : passing argument 2 of ‘memcpy’ makes pointer from integer without a cast [enabled by default]