首页 > 解决方案 > 为什么我的数组值与这里的全局变量不匹配?

问题描述

我在这里有一个问题:(我在这里创建了多个全局变量并将它们放入一个数组中。在功能中extractLabel(),我用二进制代码值填充这些变量variable = binarycode。我打印出来,一切都很好。然后我从数组。但是变量的值是 0。但是这些变量不应该在数组中具有相同的值吗?如果不是,我该如何解决这个问题?

感谢您的帮助!

#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <array>
#include <math.h>
#include <algorithm>
#include "Client.hpp"



static long long a_word = 4294967295;
static long long c_word;
static long long c_label1;
static long long c_label2;
static long long c_label3;
static long long c_label4;
static long long c_label5;
static long long c_label6;
static long long c_label7;
static long long c_label8;
static std::vector<bool> binCode;
static std::array<long long, 8> c_tokens = {c_label1, c_label2, c_label3, c_label4, c_label5, c_label6, c_label7, c_label8};



void executeClient() {
    receiveValue();
    calculateDecBin();
    extractLabel();
}

void receiveValue() {
    c_word = a_word;
}

void calculateDecBin() {
    while (c_word) {
        int rest = c_word % 2;
        c_word = c_word / 2;
        binCode.push_back(rest);
    }
    std::reverse(binCode.begin(), binCode.end());
}

void extractLabel() {

    std::cout << "Label values:" << std::endl;
    for(int i = 0; i < 8; i++) {
        c_label1 = stoll(std::to_string(c_label1) + std::to_string(binCode[i]));
    }
    std::cout << c_label1 << std::endl;

    for(int i = 8; i < 10; i++) {
        c_label2 = stoll(std::to_string(c_label2) + std::to_string(binCode[i]));
    }
    std::cout << c_label2 << std::endl;

    for(int i = 10; i < 26; i++) {
        c_label3 = stoll(std::to_string(c_label3) + std::to_string(binCode[i]));
    }
    std::cout << c_label3 << std::endl;

    for(int i = 26; i < 27; i++) {
        c_label4 = stoll(std::to_string(c_label4) + std::to_string(binCode[i]));
    }
    std::cout << c_label4 << std::endl;

    for(int i = 27; i < 28; i++) {
        c_label5 = stoll(std::to_string(c_label5) + std::to_string(binCode[i]));
    }
    std::cout << c_label5 << std::endl;

    for(int i = 28; i < 29; i++) {
        c_label6 = stoll(std::to_string(c_label6) + std::to_string(binCode[i]));
    }
    std::cout << c_label6 << std::endl;

    for(int i = 29; i < 31; i++) {
        c_label7 = stoll(std::to_string(c_label7) + std::to_string(binCode[i]));
    }
    std::cout << c_label7 << std::endl;

    for(int i = 31; i < 32; i++) {
        c_label8 = stoll(std::to_string(c_label8) + std::to_string(binCode[i]));
    }
    std::cout << c_label8 << std::endl;


    std::cout << "array values:" << std::endl;
    for(int i = 0; i < c_tokens.size(); i++) {
        std::cout << c_tokens[i] << std::endl;
    }
}

标签: c++

解决方案


您正在混淆值和引用。使用变量c_tokens的当前值初始化数组。c_labeli由于它们是静态的,因此它们被初始化为 0,这说明您在数组中找到了 0 个值。

但是当您稍后更改c_labeli变量的值时,它们与数组完全不同,并且c_tokens.


推荐阅读