简体   繁体   中英

Reassigning const char array with unknown size

So i have this 2 arrays inside my main function:

const char* basket[];
const char* basket_peach[] = {"1 1111 2 0000","2 2222 2 0000", 0};
...
    if (strcmp (c_id,"somebasketid") == 0){
        basket = basket_peach;
    }
...

If i try to do this:

...
    if (strcmp (c_id,"somebasketid") == 0){
         const char* basket[] = basket_peach;
    }
...

My main function tell me this " error: use of undeclared identifier 'basket'"

Any good idea how to do this one ?

Simply put, you can't assign an array in C and C++.

Moreover, the following will not even compile:

const char* basket[];

Arrays must be declared with an explicit size (inside the [] ) or an initializer list from which the compiler can deduce the size.

If you're writing C++, what you really need is a vector :

std::vector<const char*> basket;
std::vector<const char*> basket_peach = {"1 1111 2 0000","2 2222 2 0000", 0};
...
    if (strcmp (c_id,"somebasketid") == 0){
        basket = basket_peach;
    }

The above will work as you expected. Better yet, replace const char* with string as well:

std::vector<std::string> basket;
std::vector<std::string> basket_peach = {"1 1111 2 0000","2 2222 2 0000", ""};
...                                                          NOTICE THIS! ^^
    if (c_id == "somebasketid"){
        basket = basket_peach;
    }

This will also work as you'd expect.

You need room for basket

const char* basket[]; /* Array of pointers with 0 length */
const char* basket_peach[] = {"1 1111 2 0000","2 2222 2 0000", 0};

should be

const char *basket_peach[] = {"1 1111 2 0000","2 2222 2 0000", 0};
const char *basket[sizeof(basket_peach) / sizeof(basket_peach[0])];

basket = basket_peach;

you can't assign to an array in this way, use a loop:

for (size_t i = 0; i < sizeof(basket) / sizeof(basket[0]); i++) {
    basket[i] = basket_peach[i];
}

or declare basket as a pointer to pointer:

const char *basket_peach[] = {"1 1111 2 0000","2 2222 2 0000", 0};
const char **basket;
...
basket = basket_peach;

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