我正在尝试确定此代码是什么?
#include <cstdlib>
#include <iostream>
#include<string.h>
using namespace std;
char *skip(char *p,int n)
{
for (;n>0;p++)
if (*p==0) n--;
return p;
}
int main(int argc, char *argv[])
{
char *p="dedamiwa";
int n=4;
cout<<skip(p,n)<<endl;
}
当我在dev c ++中运行它时,它写道
`basic_string::copy`
当我在ideone.com上运行它时,它写道
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:15: warning: deprecated conversion from string constant to ‘char*’
prog.cpp:18: warning: ignoring return value of ‘int system(const char*)’, declared with attribute warn_unused_result
最佳答案
它跳过char数组的n个字符。
它将第一个参数解释为指向字符数组的指针
至少包含n个空字符,并在
第n个这样的空字符。就其本身而言,如果没有
您将正确的输入传递给它。
由于您传递了一个简单的以null终止的字符串,因此它没有定义
行为,因为在其输入中只有一个这样的空字符。它
将在字符串末尾之后访问内存。
关于编译错误,在C ++中,常量字符串的类型为
const char*
,而不是char*
,您应该检查系统返回
错误功能。由-Sylvain Defresne
带有大括号的代码版本可能有点
对您来说更具可读性:
using namespace std;
char *skip(char *p,int n){
for (;n>0;p++)
if (*p==0) {
n--;
}
return p;
}
要摆脱错误:
int main(int argc, char *argv[])
{
// cast the string which is of the type const char* to the
// type of the defined variable(char*) will remove your warning.
char *p= (char*) "dedamiwa";
int n=4;
cout<<skip(p,n)<<endl;
}