Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating dynamic array of string c++

I am struct to a very basic question. I want to create dynamically an array of string in c++.

How can I do that ?

This is my attempt:

#include <iostream>
#include <string>
int main(){
    unsigned int wordsCollection = 6;
    unsigned int length = 6;

    std::string *collection = new std::string[wordsCollection];
    for(unsigned int i = 0; i < wordsCollection; ++i){
        std::cin>>wordsCollection[i];
    }
    return 0;    
}

But it giving the following error

error C2109: subscript requires array or pointer type

What's the error ?

And also if I'am getting input number from user, from std::cin can I create an array of that size statically ?

like image 481
Abdul Samad Avatar asked Jan 20 '12 22:01

Abdul Samad


People also ask

Can you dynamically create an array in C?

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

Is string a dynamic array?

Any character string can be a dynamic array. A dynamic array is a character string containing elements that are substrings separated by delimiters.

How do you declare a string dynamically?

Allocating Strings DynamicallyEdit In duplicating a string, s, for example we would need to find the length of that string: int len = strlen(s); And then allocate the same amount of space plus one for the terminator and create a variable that points to that area in memory: char *s2 = malloc((len + 1) * sizeof(char));

How do you create a dynamic array?

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.


1 Answers

use std::vector<string> or std::list<string> over hand rolling it.

like image 197
rerun Avatar answered Sep 20 '22 15:09

rerun