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?
Enter the length of string 1: 5thenPlease enter string 1: helloBe Careful, while you can store 5 characters'h''e''l''l''o', in an array [5] char, it will NOT be a string of characters. (there is no nul-terminating character at the end -- which would require 6-characters of storage) Any attempt to use the array containing"hello"as a string will result in Undefined Behavior as the string-function madly searches all through your stack looking for a nul-character...atoi(argv[1])-- it provides Zero error checking capabilities (what ifargv[1] = "duck"?. Instead usestrtolwhich provides solid error handling capabilities.argcto assure that the user actually entered a parameter. If no parameter entered, the output aUSAGEstatement (fprintf( stderr, (USAGE: %s [numberOfStrings]\n", argv[0] );` then callexit( EXIT_FAILURE )whereexit()andEXIT_FAILUREare found instdlib.h