I've resumed C coding for fun after a several year absence.
I've given myself an exercise to safely copy text from standard input to strings using fgets()
, and copy to a string just big enough, i.e. only with enough capacity to hold the no. of chars I've actually typed, ultimately to make lists, stacks etc. from scratch, in other words, playing with pointers.
The only way I've managed this smells of kludge to me, as I'm defining the destination string variable for strcpy()
late in the control flow. Is there a more elegant/dynamic way to do this?
#inlcude <stdio.h>
#include <string.h>
#define MAXLENGTH 20
int main(int argc, char *argv[]) {
char message[MAXLENGTH];
printf("Enter a string: \n");
fgets(message, MAXLENGTH, stdin);
/* various tests here, omitted for brevity */
char destinationString[strlen(message)];
/*
* Just testing to prove that
* the strlen() of the destination
* string is LESS than MAXLENGTH
*/
printf("Here's the strlen() of destinationString: %lu\n", strlen(destinationString));
printf("Here's the sizeof() destinationString: %lu,\n" sizeof(destinationString));
printf("Here's the contents of the copy: %s", destinationString);
return 0;
}