gpt4 book ai didi

c++ - 整数作为 8 传递给函数,但函数内部的值是 -439854520

转载 作者:行者123 更新时间:2023-11-30 03:23:01 25 4
gpt4 key购买 nike

在 main 内部,我有以下调用 pad_string 的 block 。由于某些奇怪的原因,在 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;
}
}

最佳答案

函数声明与其定义之间的返回类型不匹配。原型(prototype)是:

std::string pad_string(std::string s,int total);

但是实现是:

void pad_string(std::string s,int total) { ... }

调用者和被调用者之间的不匹配可以解释为什么参数在运行时出现损坏。

关于c++ - 整数作为 8 传递给函数,但函数内部的值是 -439854520,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com