0

Can someone help me understand what I'm doing wrong in this C++ function in a file titled, "Block.cpp?"

void Block::MineBlock(uint32_t nDifficulty) {
    char cstr [nDifficulty + 1];

    for (uint32_t i = 0; i < nDifficulty; i++) {
        cstr[i] = "0";
    }

    cstr[nDifficulty] = "\0";

    string str(cstr);

    do {
        _nNonce++;
        _sHash = _CalculateHash();
    } while (_sHash.substr(0, nDifficulty) != str);

    cout << "Block mined : " << _sHash << endl;
}

I'm not sure what I'm doing wrong...I get the error: expression must have a constant value; the value of parameter "nDifficult" (declared at line 14) cannot be used as a constant.

For reference, the "Block.h" header file reads as follows.

#pragma once

#include <cstdint>
#include <iostream>

using namespace std;

class Block {
public:
    string sPrevHash;

    Block(uint32_t nIndexIn, const string &sDataIn);

    string GetHash();

    void MineBlock(uint32_t nDifficulty);

private:
    uint32_t _nIndex;
    int64_t _nNonce;
    string _sData;
    string _sHash;
    time_t _tTime;

    const string _CalculateHash();
};
Xenilo
  • 25
  • 5
  • Instead of the `for` loop you can use the string constructor `string str('0', nDifficulty);` – Devolus Apr 07 '21 at 17:25
  • The variable-length array problem aside, `cstr[nDifficulty] = "\0"` will not do what you think. Use `cstr[nDifficulty] = '\0'` instead (note the *single* quotes). Or better, yet, `string str(nDifficulty, '0');` and skip `cstr`altogether. – Some programmer dude Apr 07 '21 at 17:27
  • The value of `nDifficulty` is not known until runtime, so it can't be used in `char cstr [nDifficulty + 1];` to allocate a fixed array. You will have to use `new[]` instead: `char *cstr = new char[nDifficulty + 1]; ... delete[] cstr;` or else use `std::vector` instead: `std::vector cstr(nDifficulty + 1);` Or, simply get rid of `cstr` altogether and just use `string str` by itself, you can `resize()` it to `nDifficulty` length and then fill it as needed. – Remy Lebeau Apr 07 '21 at 17:28

0 Answers0