Array of symbolic pointers, cannot compile

Hey guys. I wanted to try the exercise Array of symbolic pointers. It seems i am missing something for my array. I need second opinion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
    char *str[3]={{"red"},{"yellow"},{"white"}};
    for(int i=0; i<3; i++)
    {
        cout<<str[i]<<endl;
    }
    cout<<str[2][0]<<str[0][4]<<str[1][0];
    cout<<str[2][3]<<str[0][3]<<str[1][4]<<endl;

    system("pause");
    return 0;
}
Last edited on
closed account (37oyvCM9)
That does exactly what you are asking it to?

str[2][0] == white string first char
str[0][4] == red string past end(highest is [2]
str[1][0] == yellow string first char
str[2][3] == white string fourth char
str[0][3] == red string past end(highest is [2]
str[1][4] == yellow string 5th char

hope this helps
I had to be exact here, sorry for that. CodeBlocks gives me some problem at line 6.
closed account (37oyvCM9)
compiled fine for me but im using MVS community
closed account (37oyvCM9)
whats the error?
That's actually helpful. I guess the code is not the problem. Hmm. I plan to use MVS for C# i guess i will add the C++ option on it as well. CodeBlocks is not kind to me all the time.

Thank you very much, guys !
1. const needed (the type of a narrow string literal is array of const char)
2. In the braced-init-list omit braces around the initialiser for a scalar.

1
2
// char *str[3]={{"red"},{"yellow"},{"white"}};
const char* str[3] = { "red", "yellow", "white" } ;

JLBorges. This actually worked fine! "const" wasn't a must, but the braces change did the thing.
Thanks, mate!
> "const" wasn't a must

With a conforming compiler, const is a must.

To force the GNU compiler to conform to standard C++ (to the extent that it is capable of conforming),
compile with -std=c++14 -pedantic-errors

1
2
3
4
int main ()
{
    char *str[3]={ "red", "yellow", "white" };
}


LLVM clang++: error: ISO C++11 does not allow conversion from string literal to 'char *'
GNU g++: error: ISO C++ forbids converting a string constant to 'char*'
http://coliru.stacked-crooked.com/a/b02063c0df1d0d65
Topic archived. No new replies allowed.