Solution for Exercise 20-5
ex2005
#include <stdio.h> #include <stdlib.h> int main() { char *input1,*input2; char *i1,*i2; input1 = (char *)malloc(sizeof(char)*1024); input2 = (char *)malloc(sizeof(char)*1024); if(input1==NULL || input2==NULL) { puts("Unable to allocate buffer! Oh no!"); exit(1); } puts("Type something long and boring:"); fgets(input1,1023,stdin); puts("Copying buffer..."); i1=input1; i2=input2; while(*i1 != '\n') *i2++=*i1++; *i2 = '\0'; printf("Original text:\n\"%s\"\n",input1); printf("Duplicate text:\n\"%s\"\n",input2); return(0); }
Notes
* Line 7 declares two char pointer variables I use in the code to copy the string, i1
and i2
. That's because I want to keep the original locations in the input1
and input2
variables.
* The copying action takes place starting at Line 21 where both i1
and i2
are initialized. That's two statements on a single line.
* The while loop at Line 22 copies the text, setting up the condition to stop copying when the pointer *i1
contains the newline character.
* Line 23 is one of those "jam it all on one line" statements favored by many C programmers. It works because the pointer operator *
binds more tightly to the pointer variable than the increment operator. So the effect is that a character is copied from pointer i1
to i2
, then both pointers (the memory addresses) are incremented.
* Line 23 could be split up as follows:
Either solution is fine, or if you managed to duplicate the string in another manner, that's okay too.
* Line 24 is required to cap the second string with the null character, \0
. Without that terminating character, the duplicate string display might include random characters. The variable i2
doesn't need to be incremented; after the while loop is complete, it automatically points to the end-of-string position where the null character needs to go.
* Here is sample output:
* The net effect of the code is to remove the newline added by the fgets() function.
Copyright © 1997-2024 by QPBC.
All rights reserved