创建我自己的strcpy函数

时间:2014-09-10 17:04:36

标签: c++

我正在尝试创建自己的str复制功能。我收到一个错误,告诉我strcopy在这个范围内没有被解雇 strcopy(甲板[I] .suit,源[]);是我的错误发生了。请帮忙!

#include <fstream>
#include <iostream>
using namespace std;

struct{
char suit[];
char rank[];
int cvalue;
};
int main()
{
char source[] = "name";
cards deck[52];

strcopy(deck[].suit,source[]);
}

void strcopy(char destination[], char source[])
{
for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++)
{
destination[i] = source[i];
}
}

2 个答案:

答案 0 :(得分:0)

首先,您忘记指定结构的名称。我认为它应该有名称cards

结构中定义的数组也必须定义为具有大小。

struct{
char suit[];  // What is the size of the array?
char rank[];  // What is the size of the array?
int cvalue;
};

函数strcopy必须在它的isage之前声明。

功能本身是错误的。

我不会发明一个新的函数算法,并按以下方式编写

char * strcopy( char destination[], const char source[] )
{
   char *p = destination;

   while ( *p++ = *source++ );

   return destination; 
}

答案 1 :(得分:0)

您正在使用&#39; strcopy&#39;在编译器知道有一个函数之前的函数。在C / C ++中,您必须在顶部定义它,或者通过提供函数的原型来提供有信息的信息。

所以要么像这样移动它:

void strcopy(char destination[], char source[])
{
    for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++)
    {
        destination[i] = source[i];
    }
}

int main()
{
    char source[] = "name";
    cards deck[52];

    strcopy(deck[].suit,source[]);
}

或在使用之前添加原型:

void strcopy(char destination[], char source[]);

int main()
{
    char source[] = "name";
    cards deck[52];

    strcopy(deck[].suit,source[]);
}

void strcopy(char destination[], char source[])
{
   for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++)
   {
       destination[i] = source[i];
   }
}

有关更多信息,您也可以在维基上看到它:
http://en.wikipedia.org/wiki/Function_prototype

我还构建了代码以提高可读性;)