1

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 ?

1
  • 2
    Enable all warnings for your compiler. Then study arrays and pointers. Commented Mar 5, 2015 at 8:27

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but when trying your first solution , i can't assign a list . non-aggregate type 'std::vector<const char *>' cannot be initialized with an initializer list
It should work. Did you include <vector>? Or are you using an old/non-conforming version of C++? Related: stackoverflow.com/q/16087886/3425536
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.