2010-12-19 34 views
0

我是新来编程,并被赋予一个任务,使一个数组放入其他具有以下条件的函数:目标数组中的变量将只重复一次,源和目标数组将相同尺寸。 我想出了一个功能:如何在取消重复变量时将一个数组更改为另一个数组?

int RemoveDup (int src[],int dst[]) 
//recive two array compare them and copy the src array to dst,and only the none reacuring 
//numbers,the arrays must be from the same size 

{ 
int size_src; 
int size_dst; 
int i,n=0; 
size_src = sizeof(src)/sizeof(int);//determine the size of source array 
size_dst = sizeof(dst)/sizeof(int);//determine the size of destination array 
if (size_src = size_dst);//checks that the array are in the same size 
{ 
for(i = 0;i < size_src;i++)//the loop for advancing the copying process 
{ 
dst[i] = src[i]; 
} 
while (i<size_dst) 
{ 
dst[i] = dst[i++]; 

if (dst[i] = dst[i++])//relay on the fact that if the function will find a similar varibale, the tested varibale will be set to 0 and the other one will come out clean in the check 
dst[i] = 0;//eliminating the varibale in that specific address 
} 
} 


return dst [i]; 

,但它似乎并不工作,不知道它是怎么了。 任何帮助或线索将不胜感激。

+1

要学的第一件事就是正确*缩进代码。否则,阅读左边排列的所有代码是非常困难的。 – 2010-12-19 21:32:44

+0

@david:您会注意到编辑器中的小工具栏图标。标有'{}'的块将代码块呈现出来,这正是Anon对你所提出的问题。编辑页面的侧边栏中还有其他格式化选项。 – dmckee 2010-12-19 21:33:05

+1

这是功课吗? – t0mm13b 2010-12-19 21:33:59

回答

0

在C中,你不能声明一个函数,它的参数是一个数组。当您使用数组声明符作为函数参数时,该类型会静默地调整为对应的指针类型。任何显式数组大小(如果指定)都会被丢弃。

换句话说,当你使用这个:

int RemoveDup (int src[],int dst[]) 

它是完全等价的:

int RemoveDup(int *src, int *dst) 

现在应该是显而易见的,为什么sizeof(src)/sizeof(int)不会做你想要的计算它要做的。

2

我注意到您在使用int src[]作为参数的函数中使用了sizeof(src)。这不是在做你认为它正在做的事情。在C中,数组的大小不会随着数组本身传递给函数(与您可能熟悉的某些其他语言不同)。您必须将实际大小作为单独参数传递。

此外,一些printf()声明肯定会有助于您的调试工作。确保价值观是你认为他们应该是的。希望你可以访问一个交互式调试器,这对你也可能非常有用。

+0

应该指出,当你做sizeof(arr)/ sizeof(int)和arr时有一个数组类型,它会*告诉你数组中有多少个元素。只是在这种情况下'src'有一个指针类型('int src []'是写入'int * src'的另一种方式),并且没有办法将数组传递给函数而不是指针。 – sepp2k 2010-12-19 21:48:08

0

事实上,有可能使一个函数接收一个数组而不是一个指针(当然,给定的数组的大小是预先定义的)。

所以你可以使用:

int RemoveDup(int src[M],int dst[N]){ 
    . 
    . 
    . 
return whatever; 

我会同意虽然这使用指针更好。 在我看来,你应该编写一个递归函数来使用当然指针。 ,以便下一次调用是(* src + 1),以便查看下一个单元格。 退出条件是:

if (sizeof(src) == 0) { 
//exit recursion statement. 
} 
相关问题