Question about Arrays and Strings

Question 1: About Arrays

Must I specify a size when initializing an array?

In my program the user enters a number into the console, and i want to create an array of that size.


Question 2: About Strings
Can I make string arrays? And why isn't a string a data type?



I appreciate any help!
1: Yes, unless you use dynamic memory allocation via new or malloc.

2: Yes. std::strings are a typedef for a basic_string of chars, which is an STL container, not an base type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int n,o;

  cout << "How many questions do you wish to answer?" << endl;
  cin >> n;
  cout << "How many characters will you use per answer?" << endl;
  cin >> o;
  char userAnswers[n][o];

  return 0;
}


I couldn't figure out how to do the DMA. But not even this seems to work for me. I get these errors:

expected constant expression
cannot allocate an array of constant size 0
expected constant expression
cannot allocate an array of constant size 0
missing subscript
unknown size
You will need to do this:

 
char* userAnswers = new char[n][o];


To make an array of strings instead, just use string instead of char. Although I would suggest using a vector, since then you won't have to prompt them for how many questions they are going to answer. Also, if you use strings, you don't need a question for how many characters per answer, since strings are dynamically sized for you.
Topic archived. No new replies allowed.