2014-09-10 186 views
-2

我想创建我自己的str复制函数。我得到一个错误,告诉我strcopy在这个范围内没有被降效 strcopy(deck [i] .suit,source []);是不是我的错误发生。请帮助!创建我自己的strcopy函数

#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]; 
} 
} 
+0

编译器错误是正确的。在您尝试使用它的地方未声明“strcopy”。它后来被声明,但C++编译器是天真的,它需要知道该函数存在于被调用的地方。 – jalf 2014-09-10 17:07:31

+0

请至少google你的错误。 – djechlin 2014-09-10 17:10:22

+0

感谢所有的帮助家伙,即时通讯学习代码,所以我做了一些新手的错误。 @djechlin,去锻炼什么的吧。 theres真的不需要隐藏在你的电脑后面,并且是无礼的 – matt 2014-09-10 17:39:35

回答

0

首先你忘了指定结构的名称。我认为它应该有名称cards

同样在结构中定义的数组必须被定义为具有大小。

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

函数strcopy必须在其语句之前声明。

而功能本身是错误的。

我没有发明功能的新算法,并把它写在下面的方式

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

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

    return destination; 
} 
+0

我重新输入了它,即时发布在我的真实计算机上,并在虚拟盒子中进行编程,并且这种方式更简单,但必须留下卡片。我在数组中指定了值。我的行动功能有什么问题? – matt 2014-09-10 17:19:37

+0

@jalf该函数没有意义。首先,如果目标数组从零开始并且不复制终止零,它将不会复制任何内容。 – 2014-09-10 17:24:56

+0

我看到我错了,非常感谢你! – matt 2014-09-10 17:38:29

0

你的编译器之前知道有一个你正在使用“strcopy”功能。在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[]); 
} 

或添加protoype使用它之前:

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

为了更好的可读性,我还构建了您的代码;)