在main中我有以下块调用pad_string。 由于一些奇怪的原因,在pad_string中,'total'的值为-439854520。我想知道为什么会这样?
更新:添加了完整定义和.cpp文件
int x = 8;
cout << x << endl;
std::string s("001");
pad_string(s,x);
定义
#ifndef BITS_HPP
#define BITS_HPP
//#: Converts a character into its binary representation
//as a string
std::string chr_to_binary(char c);
//@: x is desired length of string
//#: make a zero string of size x
std::string make_zero_string(int x);
//@:s is the string to be padded
//@:total is the desired total length of str
//#:pads s with as many zeros as neccessary so
//that s's total lenth equal total<D-r>
std::string pad_string(std::string s,int total);
实施
std::string chr_to_binary(char c)
{
std::bitset<8> bset(c);
return bset.to_string();
}
std::string make_zero_string(int x){
std::string s;
std::cout << x << std::endl;
for (size_t i = 0; i < x; ++i){
s.push_back('0');
break;
}
return s;
}
//@:s is the string to be padded
//@:total is the desired total length of str
//#:pads s with as many zeros as neccessary so
//that s's total lenth equal total.
//Padding occurs to left of s
void pad_string(std::string s,int total)
{
std::cout << (total) << std::endl;
int length = s.length();
std::cout << total << std::endl;
std::cout << length << std::endl;
if (length < total){
int diff = total - length;
std::cout << diff << std::endl;
std::string zerostr = make_zero_string(diff);
zerostr = zerostr + s;
s = zerostr;
}
}
答案 0 :(得分:2)
函数声明及其定义之间的返回类型不匹配。原型是:
std::string pad_string(std::string s,int total);
但实施是:
void pad_string(std::string s,int total) { ... }
调用者和被调用者之间的不匹配可以解释为什么参数在运行时出现损坏。