[英]using memset to fill an array shows garbage
I am stuck in a simple code snippet: 我陷入了一个简单的代码片段中:
#include <iostream>
#include <stdio.h>
#include<cstring>
#include <algorithm>
int main()
{
int l;
std::cin >> l;
char leading[l];
//std::fill_n(leading, l, '0');
memset(leading, '0', sizeof(char)*l);
std::cout << "->" << leading << "<- strlen=" << strlen(leading) << std::endl;
}
Here is the result of multiple runs(same problem with std::fill_n
): 这是多次运行的结果(与
std::fill_n
相同的问题):
~/test$ g++ ptr.cpp
~/test$ ./a.out
3
->000*�<- strlen=6
~/test$ ./a.out
7
->0000000<- strlen=7
~/test$ ./a.out
6
->000000<- strlen=6
~/test$ ./a.out
5
->00000<- strlen=6
~/test$ ./a.out
2
->00@��<- strlen=6
Do I have to look for another job? 我需要找其他工作吗?
UPDATE: As I will be using this array later in a sprintf
, I don't want to use a null terminator. 更新:因为稍后我将在
sprintf
使用此数组,所以我不想使用空终止符。 Is there a better alternative? 有更好的选择吗?
'0'
is not the same as '\\0'
which is probably what you wanted. '0'
是不一样的'\\0'
这就是你想要的大概是什么。 (No encoding system supported by C++ is allowed to set the character literal '0'
to have the value 0.) (不允许C ++支持的编码系统将字符文字
'0'
设置为值0。)
The behaviour on using strlen
on this memory block will be undefined. 在该存储块上使用
strlen
的行为将是不确定的。
If you want to populate with the character 0, then remember to add a NUL-terminator to the memory block, in order for the C-type string functions (and <<
for that matter) to be usable. 如果要使用字符0填充,请记住在存储块中添加一个NUL终止符,以使C类型的字符串函数(对于此问题,以及
<<
)可用。
Both strlen
and operator<<(basic_ostream&, char*)
have the precondition that the pointer arguments point to a null terminated string of characters. strlen
和operator<<(basic_ostream&, char*)
都具有指针参数指向以null终止的字符串的前提。 Your array is not null terminated and therefore you violate those preconditions. 您的数组不是以null终止的,因此您违反了这些先决条件。 As a result, the behaviour of your program is undefined.
结果,您的程序的行为是不确定的。
UPDATE: I don't with to use a null terminator.
更新:我不愿意使用空终止符。 Is there a better alternative?
有更好的选择吗?
There is no need for an alternative for strlen
since you already know the length: l
. 因为您已经知道长度:
l
所以不需要替代strlen
。
For streaming a non-null-terminated character array, you can use an iterator: 为了流式传输非空终止的字符数组,可以使用迭代器:
std::ostream_iterator<char> it(std::cout);
std::copy(leading, std::end(leading), it);
PS. PS。
std::cin >> l; char leading[l];
This is ill-formed in C++. 这在C ++中是不正确的。 The size of an array must be a compile-time constant.
数组的大小必须是编译时常量。
因为strlen和cout都依赖空终止符来指示字符串的结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.