gaurav21
gaurav21

Reputation: 13

dynamic memory allocation of strings in cpp

so here's the thing I've been working on a code for 5 hours now and logic looks good the program seems to do it's job, the only thing that keeps bugging me is dynamic memory allocation of strings. The question does not specify the initial number of strings user has to enter. Here's what I've been trying to do to dynamically take the strings :

      int t;
      cin>>t  //number of strings user wishes enter 
      char *s1[1000009];  //1000009 is the maximum number of digits each string can have
      for(i=0;i<t;i++)
      {
                s1[i]=(char *)malloc(1000009) 
                cin>>s1[i];
      }

not sure if it is the right way or not. A way through which i could store a 2D character array would also do if not dynamic strings.

Thanking you, gaurav

Upvotes: 0

Views: 456

Answers (3)

Kevin
Kevin

Reputation: 7324

Use a vector of strings instead of using malloc/new.

int t;
std::cin >> t;
std::vector<std::string> strings(t); //Create t strings
for(int i = 0; i < t; i++)
    std::cin >> strings[i]; //Read into each string

Upvotes: 5

Thomas Sparber
Thomas Sparber

Reputation: 2917

Since you tagged this question as C++ I would do it like this:

std::vector<std::string> s1(1000009);

That's all - no need to use malloc, no need to take care about destruction. If you are using C++ use the Tools you have available.

Upvotes: 1

Thomas Grockowiak
Thomas Grockowiak

Reputation: 101

i would do it like this :

int i = 0;
char **s1;
s1 = (char **)malloc(t * sizeof(char *));
while (i < t)
{
 s1[i] = (char *)malloc(1000009 * sizeof(char));
 i++;
}

the first malloc create you t line. The second one fill alloc 100000009charactere for each lines

Upvotes: 0

Related Questions