需要帮助尝试运行数组strcpy程序

时间:2014-04-28 03:35:52

标签: c++ arrays

我不确定运行此代码需要什么,我对错误感到困惑,非常感谢您的帮助。

#include <iostream>
#include <cassert>

using namespace std;

unsigned int strlen(const char s[])
{
    unsigned int n;

    for (n = 0; s[n]; n++);

    return n;
}

void strcpy(char t[], const char s[])
{
    for (int i = 0; t[i] = s[i]; i++);
}

void teststring()
{
    assert(strlen("") == 0);
    assert(strlen("A") == 1);
    assert(strlen("lime") == 4);

    cout << "valid" << endl;
}

int main()
{
    char t[2] = "";
    char s[5] = "a";
    char i[6] = "Joey";

    teststring();

    assert(strcpy(t, s) == 0);
    assert(strcpy(t, s) == 1);
    assert(strcpy(t, s) == 4);

    cout << "valid" << endl;
} 

我一直收到一个错误,说错误值不应该被忽略,因为它应该是。

我不确定我需要做什么才能让代码运行。

3 个答案:

答案 0 :(得分:1)

assert strcpy(t, s)返回0然后1,最后4

strcpy的原型表示它不返回任何内容:void strcpy(char t[], const char s[])

没有什么不等于任何东西。

答案 1 :(得分:0)

您的strcpy的返回类型为void。我不确定你在这里要做什么。没有什么东西只能没有任何东西(除非什么都没有,在这种情况下,没有什么不能等同于什么)。

答案 2 :(得分:0)

在主要功能中,我认为您应该在assert之后strlen(t) == strcpy(t, s)

我会写:

// BTW, you wouldn't strcpy(t, t) would you?
assert(strlen(t) == 0);
strcpy(t, s);
assert(strlen(t) == 1);
strcpy(t, i);
assert(strlen(t) == 4);

或者,您可以更改strcpy以返回strlen离开主要功能,如下所示:

unsigned int strcpy(char t[], const char s[])
{
    for (int i = 0; t[i] = s[i]; i++);

    return strlen(t);
}

main函数中,t[]的大小应大于s[]I[]。您已在问题中提及,但未在代码中实现它。

char t[2] = "";   // from this
char t[10] = "";  // to something like this