C代码表现得很奇怪。 [英] C code behaving strangely.

查看:149
本文介绍了C代码表现得很奇怪。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 ;

}





此代码输出:

url是/ localhost:ndex .htmlx.html



我的尝试:





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 ?

推荐答案

引用:

strcpy(c,& c [6]);

strcpy ( c, &c[6] ) ;

在上面一行中你误用 strcpy

来自文档 [ ^ ]:



In the above line you are misusing strcpy.
From the documentation[^]:

为避免溢出,目标指向的数组大小应足够长,以包含与源相同的C字符串(包括终止空字符),不应该在内存中与源重叠。
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.



使用source重叠目标就是你正在做的事情。





请注意,您的代码是 C 和<$ c $的奇怪组合C> C ++ 。您可以随时使用 C ++ 编译器编写:


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:

#include <iostream>

int main ()
{
  const char * p = "http://localhost:4000/index.html";
  std::cout << (p+6) << "\n";
}


经验法则:你应该避免strcpy到它自己。您可以为参数使用2个不同的变量。这应该可以解决这种陌生感。
Rule of thumb: you should avoid strcpy to itself. You use 2 different variables for the parameters. That should solve the strangeness.


这并不奇怪,但按设计工作。反斜杠是一个特殊符号,在普通字符串中无效,但在下面标出一些特殊字符。



要正确处理它,你需要为每个单反斜杠添加第二个反斜杠。像那样:

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:
strcpy( c , (char*)"http:////localhost:4000//index.html") ;

读入维基百科获取更多见解。


这篇关于C代码表现得很奇怪。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆