Exercise in C++ Primer

I'm reading through c++ primer and i've come to an exercise that i don't really understand.

The exercise:
Write a program to read strings into a vector. Now, copy that vector into an array of character pointers. For each element in the vector, allocate a new character array and copy the data from the vector element into that character array. Then insert a pointer to the character array into the array of character pointers.

I'm not quite sure what the exercise is telling me to do, and if im doing it the right way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <vector>
#include <cstring>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;

int main()
{
    vector<string> svec;
    string str;

    while(cin >> str)
        svec.push_back(str);

    const size_t arr_size = svec.size();
    char *pointerArray[arr_size];

    for(vector<string>::size_type ix = 0; ix != svec.size(); ++ix)
    {
        pointerArray[ix] = new char[svec[ix].size() + 1];
        strcpy(pointerArray[ix], svec[ix].c_str());
    }

    return 0;
}
Last edited on
Your code is invalid from the point of view of the C++ Standard. The size of an array shall be a constant expression known during compilation. So this statement is incorrect

char *pointerArray[arr_size];
Ahh thank you :)

I found some code from someone who solved this exercise, and they did like this:

1
2
char **pointerArray;
pointerArray = new char *[arr_size];


instead of

 
char *pointerArray[arr_size];


Would this make it legal?
I remember reading something about, when you allocate an array dynamically, you can do it without knowing its size during compilation.
I am a little bit confused about what this this line does:
char **pointerArray;
The size of an array shall be a constant expression known during compilation. So this statement is incorrect


This doesn't sound right. How would any self-reallocating container work in this model?
This doesn't sound right. How would any self-reallocating container work in this model?


He is right. Any self-reallocating container uses dynamic memory. Arrays are static memory, the memory is allocated at compile time.

Dynamic memory is different as it can be allocated in runtime.
A vector is actually an object that uses dynamic memory. It has been tested for memory leaks, which are a great factor to take into account when using dynamic memory.

See the following link here http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Ooh ok I thought he was referring to dynamic memory.

Was gonna say, what is dynamic about that if you have to know the size?
Topic archived. No new replies allowed.