c++ - Cannot sort command line arguments using strcpy -


i new c/c++ , learning command line arguments. trying sort command line arguments using strcpy, giving me bad output. e.g.


i/p :


o/p : ami i

can me on doing wrong here ? please note: running program argc=3 , running code inputs (which sorted) listed in example above. have removed loops debugging.

#include "iostream" #include "cstdlib" #include "cstring" using namespace std;  int main (int argc, char **argv)  {      char temp[100];      //sorting command line arguments     if(strcmp(argv[1],argv[2])>0)     {         strcpy(temp,argv[1]);         strcpy(argv[1],argv[2]);         strcpy(argv[2],temp);     }      cout<<argv[1]<<endl;     cout<<argv[2]<<endl;      return 0; } 

consider memory layout. when run $ ./a.out am, when program starts:

a   .   o  u  t  \0  \0  m  \0 ^                   ^     ^ argv[0]          argv[1]  argv[2] 

the write argv[1] in swapping procedure change this:

a   .   o  u  t  \0  m  \0 m  \0 ^                   ^     ^ argv[0]          argv[1]  argv[2] 

then write argv[2] change again this:

a   .   o  u  t  \0  m   \0 \0 ^                   ^     ^ argv[0]          argv[1]  argv[2] 

so when print out argv[1], read until null byte, giving ami. argv[2] read different starting point, giving i.

as galik points out, because argv[1] , argv[2] aren't sort of auto-resizing buffers. they're pointers memory. should note @ point exact layout not formally defined language; sorts of different unpredictable behaviour depending on platform you're using.

to fix issue, should create array of pointers strings you're sorting , swap pointers rather strings' values. both faster (requiring fewer bytes copied) , safer (fewer ways accidentally overflow buffers, happen in current code if 1 of inputs longer 100 characters).


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -