John
John

Reputation: 908

Declaring array of pointers to char arrays

How come I can do this:

char a[] = {1, 2};
char b[] = {3, 4, 5};

const char *r[] = {
    a, b
};

But I can't do it this way:

const char *r[] = {
    {1,2}, {3,4,5}
};

Is there any shortcut for initializing an array of pointers to arrays of different length?

Upvotes: 1

Views: 191

Answers (4)

chedy najjar
chedy najjar

Reputation: 631

this code doesn't work,

const char r[][] = {{1,2}, {3,4,5}};

fails with :

 x86-64 gcc 5.1!!error: declaration of 'r' as multidimensional array 
must have bounds for all dimensions except the first 


fix it like so:

const char r[][3] = {{1,2}, {3,4,5}};


side note: it's a bad practice to use C-like arrays in c++ use std::array if you know your values at compile time.


EDIT:

you can do this ugly hack(it compiles, but I don't know how many rockets it will launch).

const char *r[] = { (const char[]){1,2}, (const char[]){1,2,3}}; 

Upvotes: 1

Raindrop7
Raindrop7

Reputation: 3911

you can't write:

const char *r[] = { {1,2}, {3,4,5} };

because you cannot write:

r[0] = 1, 2, 3; // but you can r[0] = "1, 2, 3";

to initialize your array of pointers to char you can:

const char *r[] = {
    {"1,2"}, {"3,4,5"}};

so r is a an array of pointers to char.

Upvotes: 0

Peter
Peter

Reputation: 36597

The first form works because, when used like this, the name of each array is converted to a pointer (to its first element). Since the result of the conversion is a char * it can be stored in an array of char *.

The second form doesn't work since {1,2} and {3,4,5} are (initialisers for) arrays, and arrays are not pointers. An unnamed array (which these are) cannot be implicitly be converted to a pointer.

The first form IS the only shortcut to initialise an array of pointers, so each pointer points to the first element of an array.

You would be normally better off using standard containers (e.g. a std::vector<std::string>) and avoid the complexity of pointers (and conversions of array names to pointers) entirely.

Upvotes: 1

Quentin
Quentin

Reputation: 63114

There is no easy solution to achieve the syntax you're looking for: these pointers have to point at some arrays, and these arrays must have an adequate lifetime.

You probably want them to be automatic, which implies declaring them as local variables the way you did.

You could achieve sort of what you want with dynamic allocation, i.e:

const char *r[] = {
    new char[]{1,2}, new char[]{3,4,5}
};

... in which case the arrays will have sufficient lifetime, but then you have the burden of delete[]ing them at the right time. Not really a solution.

Upvotes: 1

Related Questions