Groups of characters within arrays

Hi there.

I am trying to work out the coding for having an array with characters within the array. For example, if I declared a variable of type "int":

int items[5];

I want to put, for instance, the word "milk" at item[0], the word "bread" at item[1] and the word "eggs" at item[2].

I realise I would have to tell the array (variable?) to be of type "char" but it seems that specifying, for example, an array like:

char items[20];

just makes it so that the variable "items" can accept up to 20 characters. I want to know how to make the 20 represent 20 slots or elements or whatever and accept strings of characters, say, 20 characters long for each slot.

Can anyone give me insight into this?

Thanks.
You can use a bidimensional char array: char items[20][20] or an array of strings string items[20]
If you want to play with pointers, you could also use an array of char pointers:
char* items[20]

You would have to malloc() and free() every string you put in there though, unless you are referring to some const string in your program...

A common technique when using hardcoded data is to do something like:
1
2
3
4
5
6
7
8
9
const char* POSSIBLE_ITEMS[] =
  {
  "bread",
  "cereal",
  "eggs",
  "milk",
  "orange juice",
  NULL
  };

If that fuzzies your brain any, stick with Bazzy's answer. Good luck!
Last edited on
Thanks Bazzy and Duoas.

Bazzy, how would I declare this "string items[20]"?
I tried to put in string instead of char and string doesn't come up as blue in Visual C++ 2008. Or, could you give me an example of how to use the bidimensional char arrays?

I tried it this way:

char items[20][20]

then later in the program I've got:

cout<<"Enter a first item: ";
cin>>items[0][0]
cout<<"Enter a second item: ";
cin>>items[0][1];

The program terminates incorrectly with this code. Any suggestions?
Thanks.


Last edited on
Strings are much easier than character arrays.
You need to #include<string>:
1
2
3
4
5
6
7
#include <string>
#include <iostream>
using namespace std;

string items[20]; // if using namespace std;

std::string items[20]; // if not 
Wow! Thanks so much. It worked. I've wanted to know how to do that string stuff for ages.


Thanks heaps.
Topic archived. No new replies allowed.