搜索数组成员之间差异的函数

我需要编写一个函数,如果它找到了数组成员之间的差异,它将返回true。

我的代码是:

int func1(int *str) { int i; for(i=0;i<*(str+i);i++) { if(*(str+i) == *(str+i+1)) { return 1; } } return 0; } 

我必须用指针实现它。

上面的代码不起作用(逻辑上)。

有人可以帮忙吗?

更新:

我已将代码更改为以下内容:

 int func1(int *str) { int i,temp=0; for(i=0;i<10-1;i++) { if(*(str+i) == *(str+i+1)) { temp++; if( temp == 10 ) { return 1; } } } return 0; } 

新代码有什么问题?

这看起来像我的作业,所以我不想破坏乐趣,但有一点关于C我想提一下:有一个指向某个数组的指针并没有告诉你有关数组大小的任何信息。 所以你的函数需要一个指针和一个第二个size_t参数(或者是一个指向数组最后一个元素的指针)。

你的函数只接受一个数组指针,对于比较而言似乎太少了。

您必须添加一个指定数组长度的参数,或者实现某种“策略”,例如使用特定值终止数组。

您还应该考虑使用标准的memcmp()函数。

我不明白这个问题(目前还不清楚你想要实现的目标)……

正如其他人已经说过的那样,你的arrays上没有边界检查,这是错误的……

以下是您的代码的其他一些反馈:

 // func1 - consider giving functions a meaningful name, it helps people to // understand what the function is supposed to be doing.... // In this instance, it might have been helpful to identify what the expected // return values / inputs of the function are... int func1(int *str) { int i; // Start a counter at 0, loop (adding 1) while // the current value of the counter is less than, the value held in the // array so, {1,2,3,4,0,7} Would terminate on the 0 // This: {1,20,7,14,0,7} Would also terminate on the 0 // This seems wrong, but again, it's unclear what you're trying to do here. for(i=0;i<*(str+i);i++) { // If the current element of the array // is the same as the next element of the array if(*(str+i) == *(str+i+1)) { // return 1 - two numbers next to each other in the // array are the same? return 1; } } // Either: The array contained a digit less than the counter, // Or: It didn't contain two numbers that were the same next to each other. // This seems a bit wrong?!? return 0; } 

如果你展示了什么输入,你期望返回什么样的返回值,那么你的问题可以得到改善(以获得更有用的答案)。

基于此'我将需要编写一个函数,如果它在数组成员之间找到差异,它将返回true。

在伪代码中,您似乎想要:

 // Loop, checking we don't overflow. No point checking the last element as // there's nothing after it to check... for (count = 0 to arraysize -1) { // If the current element != the next element, we've found a difference?!? if(arrayElement[count] != arrayElement[count+1) { return true } } return false 

更新:

在你的新代码中......

 // You're still assuming the size of 'str' int func1(int *str) { int i,temp=0; // Loop while i < 9, ie 9 times. for(i=0;i<10-1;i++) { if(*(str+i) == *(str+i+1)) { temp++; // Temp can never == 10, you're only going round the loop 9 times... // Maybe it should be (temp == 10-1), but I don't know where the // 10 comes from... if( temp == 10 ) { return 1; } } } return 0; } 

这个:

 if(*(str+i) == *(str+i+1)) { temp++; // Temp can never == 10, you're only going round the loop 9 times... if( temp == 10 ) { return 1; } } 

可能:

 // return 0 (FALSE) on first difference if(*(str+i) != *(str+i+1)) { return 0; } 

如果您在函数末尾更改了return 0return 1