简体   繁体   中英

Set an array to different array of unknown size

So I've been programming for my arduino which is some variant of c++. I have been writing a program to tick through every number of a 4 digit seven segment display. I have been having trouble setting my pins[] to different arrays of different lengths.

For example, displaying one means 2 pins will be on, which are expressed in the array int one[] = {1,2}; and displaying four takes four pins int four[] = {1,2,3,4}; .

What I've been trying is:

int pins[] = null;
int one[] = {1,2};
int four[] = {1,2,3,4};
switch(num) {
    case 1: pins = one; break;
    case 4: pins = four; break;
}

However this has been causing problems and isn't letting me upload it because things just break everywhere.

I have a limited knowledge of of c++, only that it's similar to Java, which I know quite a bit about.

I feel like I'm feeding sharks with insufficient protection, and this one bit in my code is bugging me.

My question is how do you initialise an array, but then change it later on?

As written, that won't compile because pins doesn't have a defined size and assigning an array to another array of a different size is not allowed. However, you can use a pointer to an array to achieve what you appear to be attempting:

int one[] = {1,2};
int four[] = {1,2,3,4};
int* pins = nullptr; // use NULL if your compiler doesn't support C++11.
size_t pinslen = 0;

switch (num) {
case 1:
    pins = one;
    pinslen = sizeof one;
    break;
case 4:
    pins = four;
    pinslen = sizeof four;
    break;
}

int one[] = {1,2}; , int four[] = {1,2,3,4}; are not the same type, we have int one[2] and int four[4] . They both may decay to int* but you loose the size information and should keep the size on your own.

A possibility is to use std::vector as follow:

std::vector<int> one = {1, 2};
std::vector<int> four = {1, 2, 3, 4};
std::vector<int>* pins = nullptr;
switch (num) {
    case 1: pins = &one; break;
    case 4: pins = &four; break;
}

And for C++03:

const int c_one[] = {1, 2};
const int c_four[] = {1, 2, 3, 4};
std::vector<int> one(c_one, c_one + 2);
std::vector<int> four(c_four, c_four + 4);
std::vector<int>* pins = 0;// or NULL
switch (num) {
    case 1: pins = &one; break;
    case 4: pins = &four; break;
}

Alternatively, you may want to copy in pins and don't use pointer, something like:

const int one[] = {1, 2};
const int four[] = {1, 2, 3, 4};
std::vector<int> pins;
switch (num) {
    case 1: pins.assign(one, one + 2); break;
    case 4: pins.assign(four, four + 4); break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM