How to dynamically allocate an array of strings

In summary, to dynamically allocate an array of strings in C++, you can use the new operator or the std::vector class, while in Java, you can use the new operator or the ArrayList class. The main difference between dynamic and static allocation is that dynamic allocation allows for resizing and deletion of arrays, while static allocation does not. To free the memory of a dynamically allocated array, you can use the delete[] operator or the clear() method, or the memory will be automatically freed if using a class to manage the array. It is possible to dynamically allocate an array of strings of different lengths, but proper tracking of the sizes is necessary.
  • #1
doktorwho
181
6
I was supposed to write a program that has a while loop in which two people, person1 and person2 input a string. The program runs the loop until one of the people inputs "it's over". At that time the program should exit and print out the correspodance between these two people while they were in a loop.(Formatted so that you can see what they wrote and not all combined together). For that it should use a dynamically aloocated array of strings (something like char **corr, using double pointers)
Below is the code without the memorization of the correspondance.
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  int counter = 0;
  while (1) {
     char *person1, *person2, c;
     int i = 0;
    person1 = (char*)calloc(500, sizeof(char));
    person2 = (char*)calloc(500, sizeof(char));
    printf("The person1 says: \n");
    while ( (c = getchar()) != '\n') {
      person1[i++] = c;
    }
    person1[i] = '\0';
    i = 0;
    printf("The person2 says: \n");
    while ( (c= getchar()) != '\n') {
      person2[i++] = c;
    }
    person2[i] = '\0';
   
    person1 = realloc(person1, (strlen(person1)+1)*sizeof(char));   //Freeing up unused space
    person2 = realloc(person2, (strlen(person2)+1)*sizeof(char));
   
   
        if (strcmp(person1, "it's over") == 0) {
            printf("The ending. The program will exit. \n");
            system("pause");
            break;
        }
        if (strcmp(person2, "it's over") == 0) {
            printf("The ending. The program will exit. \n");
            system("pause");
            break;
        }
        free(person1);
        free(person2);
        counter += 1;
  }
  printf("%d", counter);  \\number of times each of them sent a message.
}
I've never used ** pointer before but know that its an array of pointers. Do i now create two ** char elements to hold the conversation for each and how would i print them? How would i know when the other one finished his sentence? Do pointers in an array of pointers (char **some_name) point to strings or chars?
 
Technology news on Phys.org
  • #2
The pointer points to an element of type char. To get a string you allocate memory to the pointer of type char and length l which is the length of the string.
 
  • Like
Likes doktorwho
  • #3
You'll need something like this:
C:
int counter=0;
const char **corr=(const char **)calloc(2*sizeof(const char*));
while(1) {
  //input as before
  //realloc as before
  //test for end as before
    //now make room for 2 more lines:
  corr=(const char **)realloc(corr, 2*(counter+1)*sizeof(const char*));
  corr[2*counter]=person1;
  corr[2*counter+1]=person2;
  //do not free person1 and person2 yet
  counter++;
}
for (int i=0; i<2*counter; i++) {
  printf("%s", corr[i]); //you'll want some more formatting here
  free(corr[i]); //free it while we're at it
}
free(corr);
I'd use an array of struct { const char *p1, *p2; } instead of flat array of char * but if you have to do it that way then I did.

Also I'd keep allocated count and used count instead of just one count, and allocate some 10 items more, and only realloc when that runs out.
Memory allocation is generally slow and also causes trouble if the application is going to run for a long time. But that's not a problem here so it should work fine as it is.
 
  • Like
Likes doktorwho
  • #4
SlowThinker said:
You'll need something like this:
C:
int counter=0;
const char **corr=(const char **)calloc(2*sizeof(const char*));
while(1) {
  //input as before
  //realloc as before
  //test for end as before
    //now make room for 2 more lines:
  corr=(const char **)realloc(corr, 2*(counter+1)*sizeof(const char*));
  corr[2*counter]=person1;
  corr[2*counter+1]=person2;
  //do not free person1 and person2 yet
  counter++;
}
for (int i=0; i<2*counter; i++) {
  printf("%s", corr[i]); //you'll want some more formatting here
  free(corr[i]); //free it while we're at it
}
free(corr);
I'd use an array of struct { const char *p1, *p2; } instead of flat array of char * but if you have to do it that way then I did.

Also I'd keep allocated count and used count instead of just one count, and allocate some 10 items more, and only realloc when that runs out.
Memory allocation is generally slow and also causes trouble if the application is going to run for a long time. But that's not a problem here so it should work fine as it is.
Wow thanks a lot! Only one question. When do i then free person1 and person2? They need to be freed before the while loop goes on again, right?
 
  • #5
doktorwho said:
Wow thanks a lot! Only one question. When do i then free person1 and person2? They need to be freed before the while loop goes on again, right?
No. If you freed them, you could not print them after the conversation ends.
You need to free them after you print them.
 
  • #6
Re: casting the variable corr to const char **.

If you turn on compiler warnings you will get clearer complaints. const implies that you guarantee no changes ever to the buffer. Which is not true, if I understand what you are doing.
 
  • #7
jim mcnamara said:
Re: casting the variable corr to const char **.

If you turn on compiler warnings you will get clearer complaints. const implies that you guarantee no changes ever to the buffer. Which is not true, if I understand what you are doing.
const char ** means that the characters are not modified, but the pointers and the array can (we could not do corr[0][0]='a'; )
char *const * means that the pointers cannot be modified (we do that during corr[2*count]=person1; )
char ** const means that the array cannot be modified (we do that during realloc).
So it should be fine the way it is.
 

1. How do I dynamically allocate an array of strings in C++?

To dynamically allocate an array of strings in C++, you can use the new operator to allocate memory for the array, and then use a loop to allocate memory for each string in the array. Alternatively, you can use the std::vector class to dynamically allocate and manage an array of strings.

2. How can I dynamically allocate an array of strings in Java?

In Java, you can use the new operator to allocate memory for the array, and then use a loop to allocate memory for each string in the array. Alternatively, you can use the ArrayList class to dynamically allocate and manage an array of strings.

3. What is the difference between dynamically allocating an array of strings and statically allocating an array of strings?

The main difference between dynamically and statically allocating an array of strings is that with dynamic allocation, the size of the array can be determined at runtime, while with static allocation, the size of the array must be known at compile time. Additionally, dynamically allocated arrays can be resized or deleted during the program's execution, while statically allocated arrays cannot.

4. How do I free the memory of a dynamically allocated array of strings?

To free the memory of a dynamically allocated array of strings, you can use the delete[] operator in C++ or the clear() method in Java if you used the new operator to allocate the memory. If you used a class such as std::vector or ArrayList to manage the array, the memory will automatically be freed when the object is destroyed.

5. Can I dynamically allocate an array of strings of different lengths?

Yes, you can dynamically allocate an array of strings of different lengths. This allows for greater flexibility in managing different sizes of data. However, you will need to keep track of the sizes of each string in the array to avoid any memory leaks or errors.

Similar threads

  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
Replies
4
Views
736
  • Programming and Computer Science
Replies
7
Views
1K
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
1
Views
945
  • Programming and Computer Science
Replies
20
Views
1K
  • Programming and Computer Science
3
Replies
73
Views
4K
Back
Top