将数组动态添加到多维数组

时间:2015-10-28 21:09:21

标签: c++

我有把数组作为多维数组元素的问题。 下面的代码不能像我一样工作,但是如果我将类型从unsigned char更改为int,那么一切正常。

unsigned char CH0[4] = { 1, 2, 3, 4 };
unsigned char CH1[4] = { 8, 7, 6, 5 };

unsigned char** mPins;
unsigned char index;

void init(unsigned char size)
{
    mPins = new unsigned char*[size];
    index =0;
}

void setup(unsigned char* array){
    mPins[index] = array;
    index++;
}

main() {
   init(2);
   setup(CH0);
   setup(CH1);
}

1 个答案:

答案 0 :(得分:0)

您的代码不会打印任何内容,因为char应该用于存储字符。包含您正在使用的代码的字符是不可打印的。

此代码works

#include <iostream>

unsigned char CH0[4] = { 1, 2, 3, 4 };
unsigned char CH1[4] = { 8, 7, 6, 5 };

unsigned char** mPins;
unsigned char index;

void init(unsigned char size)
{
    mPins = new unsigned char*[size];
    index =0;
}

void setup(unsigned char* array){
    mPins[index] = array;
    index++;
}

int main() {
    init(2);
    setup(CH0);
    setup(CH1);
    for(int i = 0; i < 2 ; ++i) {
        for(int j = 0; j < 4; ++j) {
            std::cout << (int)mPins[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

输出:

1 2 3 4 
8 7 6 5