I hear that fscanf is evil and fgets outshines it in spades, however, fscanf has an addictive advantage (or so I've been told) in that it auto-allocates memory for string arguments; which makes me feel all warm and fuzzy inside! However its behaviour is oddly different when handling strings that are part of an array...
If I create a string:
and then pass this null pointer to fscanf:Code:char *mystring;
It will automatically allocate space for "mystring".Code:fscanf(stdin, "%s", mystring);
HOWEVER, if I now create an array of (lets say 10) strings (aka 10 char pointers):
And then pass one (any one, but lets use the first) of these pointers to fscanf, all of sudden it doesnt want to auto allocate memory for it anymore!:Code:char **mystrings = (char **)calloc(10, sizeof(char *));
I don't get it... "mystrings" is an array of char pointers, so "*mystrings" is a char pointer (namely the first one) just like any other char pointer, yet because it belongs to an "array", somehow fscanf won't treat it like a regular char pointer (as it did in the first example with "mystring").Code://causes memory/access error fscanf(stdin, "%s", *mystrings);
Additionally, if I go so far as to explicitly assign any pointer (lets use the first) in the array of pointers to a pre-allocated pointer:
Now it magically works again!!Code:char *mystring; char **mystrings = (char **)calloc(10, sizeof(char *)); //explicitly assign the first pointer of the array to another pointer *mystrings = mystring; fscanf(stdin, "%s", *mystrings);
Leaving my question.... is there something about scanf that it absolutely needs a pointer to have an explicit memory address (i.e. "mystring"), as opposed to it being a memory address pointed to by a pointer (i.e. "*mystring"), in order for it to auto-allocate memory for it??
OR.. have I been misinformed,... does fscanf really allocate memory for strings, or does it simply just stomp over any memory it can find on the program stack??