Tcs question print string in c using command line

#include <stdio.h>

int main(int argc,char *argv[])
{
     
    if(argc==1){
        printf("Error:Please enter atleast one argument");
        return 0;
    }
    
//Note:- argv[0] is by default 0 our input string start storing from argv[1]. So it's better to start for loop from 1

      int i,v=0,size=argc-1;
      
      char *str;//intialize pointer
      
      //allocate memory to which pointer points
      
      str=(char*)malloc(v);//intially zero
      
      //now re allocate memory as per size of input sting arguments
      for(i=1;i<=size;i++){
          
     int length=v+strlen(argv[i]);
      str=(char*)realloc(str,length);
      
      //now concatenate the string argument
      strcat(str,argv[i]);
      //give a namespace
      strcat(str," ");
      }
      
      //now print string use %s not %concatenate
      printf("%s\n",str);
      
      return 0;
      
     
     
}

No comments:

Post a Comment