指针算术,通过引用传递

时间:2014-05-29 19:17:29

标签: c++

我从过去的试卷中得到了以下问题:

考虑以下源代码:

using namespace std;

int main()
{
   char dest[20];
   printf( "%s\n", altcopy( dest, "demo" ) );
   printf( "%s\n", altcopy( dest, "demo2" ) );
   printf( "%s\n", altcopy( dest, "longer" ) );
   printf( "%s\n", altcopy( dest, "even longer" ) );
   printf( "%s\n", altcopy( dest, "and a really long string" ) );
}

为名为altcopy()的函数提供一个实现,该函数使用指针算法将C类型字符串的替换字符复制到目标(即第一个,第三个,第五个等字符)。您的答案不得使用[]运算符来访问数组索引。然后,上面的代码将输出以下内容:

dm
dm2
lne
ee ogr
adaral ogsrn

我的尝试如下:

using namespace std;

char* altcopy (char* dest, const char* str)
{
  char* p = dest;
  const char* q = str;

  for ( int n=0; n<=20; n++ )
  {
    *p = *q;
    p++;
    q++;
    q++;
  }
  return dest;
}

int main()
{
   char dest[20];
   printf( "%s\n", altcopy( dest, "demo" ) );
   printf( "%s\n", altcopy( dest, "demo2" ) );
   printf( "%s\n", altcopy( dest, "longer" ) );
   printf( "%s\n", altcopy( dest, "even longer" ) );
   printf( "%s\n", altcopy( dest, "and a really long string" ) );
}

结果是:

dm
dm2lne
lne
ee ogradaral ogsrn
adaral ogsrn

我不确定为什么它会在某些输出上重复下一个语句结果,而不是像要求的那样执行。这里有什么帮助?

3 个答案:

答案 0 :(得分:1)

您的功能至少因为它使用幻数20而无效。 该函数应该与标准函数strcpy类似,即必须复制源字符串,直到遇到终止零。

这是一个简单的函数实现

#include <iostream>

char * altcopy( char *dest, const char *str )
{
    char *p = dest;

    while ( *p++ = *str++ )
    {
        if ( *str ) ++str;
    }

    return dest;
}

int main()
{
    char dest[20];

    std::cout << altcopy( dest, "demo" ) << std::endl;
    std::cout << altcopy( dest, "demo2" ) << std::endl;
    std::cout << altcopy( dest, "longer" ) << std::endl;
    std::cout << altcopy( dest, "even longer" ) << std::endl;
    std::cout << altcopy( dest, "and a really long string" ) << std::endl;

    return 0;
}

输出

dm
dm2
lne
ee ogr
adaral ogsrn

享受:!)

答案 1 :(得分:0)

因为在你的循环中:

for ( int n=0; n<=20; n++ )
{
    *p = *q;
    p++;
    q++;
    q++;
}

你只是循环20次而不管你从字符串末尾读取随机内存的字符串长度。在大多数情况下,你可能在真正的字符之后读取0并且写下接下来就printf而言终止字符串,但有时因为字符串碰巧存储在内存中的方式你从下一个字符串中得到一些字符。

答案 2 :(得分:0)

这是因为q++正在进行两次,它跳过终止空值,然后跳到下一个字符串。 事实上,它甚至不检查终止空值。

相关问题