C program malloc with array of strings

ClockwerkSC

At the beginning of a program I need to dynamically allocate memory for an unknown number of strings with unknown number of size to later manipulate with. To get the number of strings from a user I have:

int main(int argc, char *argv[]){

int number = atoi(argv[1]);

So far so good. "number" now holds holds the number that the user inputted on the command line for executing the code. Now here comes the part I don't quite understand. I now need to dynamically store the lengths of the strings as well as the contents of the strings. For example, I want the program to function like this:

Enter the length of string 1: 5
Please enter string 1: hello
Enter the length of string 2: ...

For this I recognize that I will have to create an array of strings. However, I can't quite understand the concept of pointers to pointers and what not. What I would like is perhaps a simplification of how this gets accomplished?

Increasingly Idiotic

You know from the start you will have number strings to store so you will need an array of size number to store a pointer to each string.

You can use malloc to dynamically allocate enough memory for number char pointers:

char** strings = malloc(number * sizeof(char*));

Now you can loop number times and allocate each string dynamically:

for (int i = 0; i < number; i++) {
   // Get length of string
   printf("Enter the length of string %d: ", i);
   int length = 0;
   scanf("%d", &length);

   // Clear stdin for next input
   int c = getchar(); while (c != '\n' && c != EOF) c = getchar();

   // Allocate "length" characters and read in string
   printf("Please enter string %d: ", i);
   strings[i] = malloc(length * sizeof(char));
   fgets(strings[i], length, stdin);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related