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 ?
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.
Any character string can be a dynamic array. A dynamic array is a character string containing elements that are substrings separated by delimiters.
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));
A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.
use std::vector<string>
or std::list<string>
over hand rolling it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With