将字符数组连接在一起
Concatenating char arrays together
这是几年前我认为微不足道的事情。。。我已经有一段时间没有涉足C或C++了,现在我有一个问题导致了偏头痛。
我收到以下代码的错误:
CompressFile::CompressFile(wchar_t *WorkingDirectory, wchar_t *File)
{
int bzipError = BZ_OK;
wprintf(L"Attempting to compress %s%sn", 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: %sn", bzipCompressedOutput);
wprintf(L"Output of string raw: %sn", 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
相加,最后将.bz2
连接到bzipCompressionOutput
的末尾。
在他的书第4章的最后一页:"C++编程语言"Bjarne Stroustrup,C++的创建者说:
首选
strings
而非C样式字符串
这只是建议,但我鼓励你遵循它。
但你真正的问题是你在践踏内存——你的FileRawInput
中有而不是sizeof(FileRawInput)
wchar_t
,同样,bzipCompressedOutput
阵列中没有sizeof(bzipCompressedOutput)
,两者中都有MAX_PATH
wchar_t
。问题是sizeof
会告诉你数组中的字节数,但如果每个元素都大于1个字节,那么你就错误地告诉了wcsncpy
和wscncat
你的字符数。wchar_t
通常是2个字节:https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx这意味着您实际上是在呼叫wcsncpy(FileRawInput, WorkingDirectory, 200)
。超出已分配的内存100wchar_t
秒。更正此错误将删除您的segfault。
但是,为了打印宽字符串,您需要正确地使用%ls
修饰符来修改wprintf
。
最终,你的代码应该是这样的:
wprintf(L"Attempting to compress %ls%lsn", 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: %lsn", bzipCompressedOutput);
wprintf(L"Output of string raw: %lsn", FileRawInput);
实时示例
编辑:
OP已经默认了Bjarne Stroustrup的建议,并使用了wstring
:将字符数组连接在一起。但对于仍坚持使用这些C风格函数的其他人来说,MAX_PATH
必须足够大,以容纳wsclen(WorkingDirectory) + wsclen(File) + wsclen(L".bz2")
和L' '
字符,因此在该函数上放置if语句可能会很有用,或者:
assert(MAX_PATH > wsclen(WorkingDirectory) + wsclen(File) + wsclen(L".bz2"))
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 在 libcurl 连接池中预创建连接
- 将图形属性与 std::unique_ptr 捆绑在一起
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 为什么push_back和emplace_back结合在一起时,会有不同的行为
- 在浮点精度成为一个问题之前,可以将多少个浮点值加在一起
- 为什么在template函数广播中把两个extensor表达式加在一起不正确
- 实现具有浮点键的类似哈希表的数据结构,其中公差内的值被合并在一起
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 如何将这些连接在一起
- 将字符数组连接在一起
- C++将三个char*字符串连接在一起
- 试图创建一个函数,将两个大小不等的字符串向量中的单词连接在一起
- 将消息片段连接在一起
- 将两个基本字符串连接在一起
- 将2个字符串连接在一起
- c++:将数组连接在一起-是否可能使用指针而不复制
- 将Leap和QT连接在一起