Pointer to 2D Arrays

Here's my falty code:

1
2
3
char **scl;

scl=new[some int][another int];


This is obviosly wrong, because C::B spits this out:

1
2
3
o\Cpp\scales\scales.cpp||In constructor 'Scale::Scale()':|
o\Cpp\scales\scales.cpp|30|error: cannot convert 'char (*)[0]' to 'char**' in assignment|
||=== Build finished: 1 errors, 0 warnings ===|


I've read this site section on pointers to pointers and this seemed like the obvious solution, well looks like its not.

If it helps, scale is supposed to hold something like this:

scl --> {"C","D","E","F","G","A","B"}

Edit: typos
Last edited on
See this for reasons why you shouldn't do this, and also for the ways you can do it if you really insist on doing it:

http://cplusplus.com/forum/articles/17108/

Although, really, you'd be better off with a std::vector< std::string> > instead of a char**.
Thank's, problem not solved yet but that's just because I haven't had time to read it all, although I get the general picture.
I've implemented what I've learn from that link in the following code:

1
2
3
4
5
6
    char *p=new char[4*3];

    strncpy(&p[0],"C#",3);
    strncpy(&p[1*3],"D#",3);

    cout<<&p[0]<<endl<<&p[3];


Would you consider this a good (not evil) approuch to an array of strings?

I know I could make a class to wrap that into a nice package, but I'm just experimenting..
No, that's horrible. You can't even access a string by index, let alone append something to one. And if you find yourself using C string functions in C++, you almost certainly did something wrong.
The correct solution is a vector<string>.
vector is a bit confusing for me, I've read the reference but can't quite understand it's use.

Using vectors I don't need to allocate memory do I?
closed account (D80DSL3A)
Your original problem (one character per note) could be solved with a simple character array:
char scale[] = "CDEFGAB";. The notes could be referenced as scale[0], scale[1], etc..

Your slightly more complicated case (2 characters per note) when you changed the problem mid-thread could be handled with:
char scale[][3] = {"C#", "D#"};

Use of vectors and strings is not too much more complicated:
1
2
3
4
vector<string> scale;
scale.push_back( string("C#") );
scale.push_back( string("D#") );
cout << scale[1];// should print D# to screen 

The advantage here is that you can add cases later. You can change the content of the character arrays but you can't change the array sizes.
Last edited on
When I said "something like this" I gave a bad example as a note can be a sharp as well. I should have given an example of both.

That example was fine, I was missing one so that I could understand vector usage.

Thanks
Topic archived. No new replies allowed.