2011-10-22 70 views
0

我想确定这段代码是什么?跳过程序做什么?

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

当运行它OM开发的C++,它wrotes

`basic_string::copy` 

在i上ideone.com运行它,它wrotes

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 

回答

1

它跳过字符数组中的n个字符。

It interpret the first parameter as a pointer to an array of character containing at least n null characters, and return a pointer after the n-th such null-character. Per se, there is no undefined behavior if you pass correct input to it.

Since you pass a simple null terminated string, it has undefined behavior, as there is only one such null-character in its input. It will access memory after the end of the string.

Concerning the compilation errors, in C++ a constant string is of type const char* , not char* , and you should check the return of the system function for error. by -- 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; 
} 
3

它搜索一定数量的\0n号码\0)。它是未定义的行为,因为它在字符串结尾之后。

对于const部分,C++中的字符串文字是const。在c他们不是,但他们仍然不能修改,否则你会得到一个未定义的行为(通常是一个崩溃)(所以即使在c通常更好地宣布他们为const和现场高兴)

原因basic_string::copy的结果是在你的(编译器/实现特定,但很常见)编译的程序有一个区域,所有常量字符串被“一起”保存。所以如果你在一个结束之后去,你会去另一个的开始。所以,某个地方在可执行文件有一样的东西:

dedamiwa\0something\0somethingelse\0somethingelseelse\0basic_string::copy 
2

它解释第一个参数是指向字符的含有至少n空字符数组,第n个这样的空字符后返回一个指针。本身,如果向它传递正确的输入,则没有未定义的行为

由于您传递了一个简单的以null结尾的字符串,它具有未定义的行为,因为其输入中只有一个这样的空字符。它将在字符串结束后访问内存。

关于编译错误,在C++中,常量字符串的类型为const char*,而不是char*,您应该检查返回的system函数是否有错误。

0

跳跃过程正在请求段错误。

基本上,它增加p直到找到下一个'\ 0',并重复n次。

在最好的情况下,因为'\ 0 ...'是std :: cout的空字符串(std :: ostream &,const char *),所以不会打印任何内容。

在最糟糕的情况下,会出现鼻龙,引用comp.lang.c.