Array of Arrays?

Started by
5 comments, last by Servant of the Lord 11 years, 9 months ago
i cannot for the life of me figure out how to create the following an array of static arrays. below is a picture of what i mean. I want to be able to advanced my pointer 1 byte and hit another string. Is the following even possible?

http://craz.net/Snapper/live/view/?s=r6t
Advertisement
I think what you're looking for is char[][256]; I wrote a post about something similar a while ago... It might be what you're looking for.
What language are you using? Do you want to be able to dynamically add and remove rows from the outer array?
I need to dynamically add rows and im using C++.

FastCall22 - I will look at your post and see if it's what im looking for
Have you tried std::vector<std::string>?

If you really need the inner arrays to have an upper limit of 255 characters for some reason, I recommend writing a type for that and putting this type in a vector. At its simplest this could be wrapping a raw array in a struct. A better approach might internalise the details such as ensuring correct handling of the ever troublesome NUL character (assuming you want to use C-style strings).

struct short_string
{
public:
// std::string-like interface
private:
char data[256];
};

// Later
std::vector<short_string> v;
You may use std::array (fixed-size array) in conjunction with std::vector (dynamic array): http://ideone.com/W2RGh

The standard guarantees that both std::array and std::vector are contiguous -- and, hence, support pointer walk-through that you desire:
http://herbsutter.co...-be-contiguous/

If you do that, please be wary of the need to adopt a convention regarding the gaps -- as recommended above, NUL terminator might be a good idea.

However, if you want you can also access each individual word with the usual indexing (MyWords[0], MyWords[1], MyWords[2], ...) which I believe might be easier on the readers of your code :-)
Another common thing done for 2D arrays is just use a 1D array and multiply.

//Creation:
std::vector<MyType> myArray;
myArray.resize(HEIGHT * WIDTH);



//Accessing by x and y:
int index = (Y * WIDTH) + X;
myArray[index] = ...;


The benefit of a 1D array is that, unlike a std::vector< std::vector<type> >, you are sure every row is the same width, and that iteration over the vector is very easy: just iterate over it like a 1D array, but when wanting to access a 2D cell, then index as shown above.

This topic is closed to new replies.

Advertisement