Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include<iostream>
using namespace std ; 

int main ()
{
  char *c = new char(100);

strcpy( c , (char*)"http://localhost:4000/index.html") ; 


strcpy ( c, &c[6] ) ;

printf(" url is %s\n" , c  ) ; 

return 0 ;

}


This code outputs :
url is /localhost:ndex.htmlx.html

What I have tried:

I wanted to output /localhost:4000/index.html. I know that this can be done through assigning c = c+ 6 but I want to know how does the above code works ? 
Where does the number 4000 disappear and from where does the extra stuff comes from ?
Posted
Updated 6-Mar-19 21:24pm

Quote:
strcpy ( c, &c[6] ) ;
In the above line you are misusing strcpy.
From the documentation[^]:

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

Overlapping destination with source is just what you are doing.


Please note, your code is an odd mix of C and C++. Having at your disposal the C++ compiler, you might simply write:
C++
#include <iostream>

int main ()
{
  const char * p = "http://localhost:4000/index.html";
  std::cout << (p+6) << "\n";
}
 
Share this answer
 
Rule of thumb: you should avoid strcpy to itself. You use 2 different variables for the parameters. That should solve the strangeness.
 
Share this answer
 
This is NOT strange but "works as designed". The backslash is a special sign which isnt valid in plain strings but signals some special characters following.

To handle it correct you need to add a second backslash for EACH single backslash. Like that:
C++
strcpy( c , (char*)"http:////localhost:4000//index.html") ;
Read in the wikipedia for some more insights.
 
Share this answer
 
Comments
Rick York 7-Mar-19 2:31am    
Those are NOT backslashes. They are forward slashes and they are not escape characters.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900