1

I try to assign two c-strings at once:

 char **pair = {"name","joe"};

but I get error message:

 'initializing' : cannot convert from 'const char [5]' to 'char **'

But I think something like that worked for me before?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 1
    Is this C or C++? With gcc 4.7.2, try `char *pair[] = {"name","joe"};` –  May 14 '13 at 07:57
  • possible duplicate of [Simple C array declaration / assignment question](http://stackoverflow.com/questions/1582165/simple-c-array-declaration-assignment-question) –  May 14 '13 at 07:57
  • 3
    Also, visit http://c-faq.com and read about pointers. **They are not arrays.** And arrays aren't pointers either. –  May 14 '13 at 07:58

5 Answers5

8

You declare a pointer-to-pointer but the initializer is an array of pointers:

const char *pair[] = { "name", "joe" };

As noted I added the const keyword to the declaration. This is because the pointers are pointers to string literals, and literals are constant and can't be changed. Adding that const helps the programmer not to make changes by mistake to the strings in the array.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Use C++ facilities, it will save you a world of pain:

vector<string> field = { "name", "joe" };

Although maybe you need:

pair<string, string> field("name", "joe");

Or better yet, possibly:

struct Person {
    Person(const string& name) : name(name) {}
    const string name;
};

Person boss("joe");
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Joachim approach creates read-only string. That's how you create an array of const string literals.

Another way,

// MAX_LEN being the max string length.
char pair[][MAX_LEN] = {"name","joe"}; // This makes pair read-writeable, 
Arun
  • 2,087
  • 2
  • 20
  • 33
0

All answers given here are correct. What to choose depends on context:

  1. If you never changes the strings at runtime, go for Joachim Pileborg's approach
  2. If you for some reason know that strings have a fixed length, go for Arun's
  3. If neither 1 or 2, go for Peter Wood's. Note that

    vector<string> field = { "name", "joe" };
    

    requires C++11

user877329
  • 6,717
  • 8
  • 46
  • 88
0

const char *pair[] = { "name", "joe" };

This is the best solution