0
 1. char *names[5]={"Web","Security","Software","Hello","Language"};

 2. char names[5][30]={"Web","Security","Software","Hello","Language"};

what is the difference between these two ?

One I know is that (1.) first one can have desired length of string while (2.) second one can have string 29 characters with '\0'

But I am confused that what's the difference when they are passed to function and how they are passed ?

Please elaborate I am new to C++ ....

CodeFu
  • 145
  • 1
  • 14
  • 1
    Well the first one doesn't compile because string literals are `const`. – Quentin Apr 28 '15 at 13:33
  • The first one is allocating `5 * sizeof(char*)` bytes and it's storing a pointer at each index, while the second one is allocating `5 * 30` bytes and saving your strings there. P.S. That's C. – rev Apr 28 '15 at 13:33
  • warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]| It compiled but with this warning, can you please explain Quentin – CodeFu Apr 28 '15 at 13:38
  • 1
    It is not allowed by C++ standard to point to string literal without const. http://stackoverflow.com/questions/14570993/why-are-string-literals-const – senfen Apr 28 '15 at 13:40
  • 1
    @CodeLearner this is a leftover compatibility rule with an old C standard which didn't have `const`. In any case, modifying a string literal is forbidden (and will generally crash), so you're better off declaring it `const` and let the compiler catch any misuse. – Quentin Apr 28 '15 at 13:46

1 Answers1

3

The first one shouldn't compile unless you add a const; const char *names[5] = ....

Once you fix that, the first is an array of pointers, the second is an array of arrays.

If you pass them to a function, the first will decay into a pointer to a pointer, const char**, while the second will decay into a pointer to an array with 30 elements, char(*)[30].

That is,

void pointers(const char**);
void arrays(char(*)[30]);

const char *names[5]={"Web","Security","Software","Hello","Language"};
pointers(names); // Good
arrays(names); // Bad

char names[5][30]={"Web","Security","Software","Hello","Language"};
pointers(names); // Bad
arrays(names); // Good
molbdnilo
  • 64,751
  • 3
  • 43
  • 82