Целое число передано в функцию как 8, но тогда значение внутри функции равно -439854520 - PullRequest
0 голосов
/ 05 июня 2018

Внутри 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;
    }
}

1 Ответ

0 голосов
/ 05 июня 2018

Вы не соответствовали типу возврата между объявлением функции и ее определением.Прототип:

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

, но реализация:

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

Несоответствие между вызывающим и вызываемым абонентами может объяснить, почему параметр оказался поврежденным во время выполнения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...