c++ - strcpy copies content of an other array -


so have piece of code convert char array contents of struct. (no, i'm not gonna argue on whether or not right/most efficient way it)

void chararray_to_categorie(categorie &levarr, char** chararray)     {           string temp = chararray[0];         int length = temp.length();         temp = temp.substr(0, ((length<21)?length:20));          strcpy(levarr.naam, temp.c_str()); //a sloppy way use substring on char array. tried memcpy , caused same results why i'm trying way.         levarr.naam[20] = '\0';          strcpy(levarr.omschrijving, chararray[1]);           cout << endl << chararray[0] << endl << temp << endl << levarr.naam << endl << length << endl << ((length<21) ? length : 20);         _getch();          /*         input:         naam: 1234567890123456789012345678901234567890         omschrijving: lol          output:         chararray[0]: 1234567890123456789012345678901234567890         temp: 12345678901234567890         levarr.naam: 12345678901234567890lol          */      } 

as can see in ouput can see content of struct has 2 chararrays combined problem.

there lot of things suboptimal in code error comes down to:

levarr.naam[20] = '\0'; 

which should

levarr.naam[19] = '\0'; 

as arrays counted starting 0;

other things fix:

  • use save strcpy function null-terminates string , features size argument, have guarded against issue.
  • don't substring, copy many characters original string using safe function.

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -