搜索数组成员之间差异的函数
我需要编写一个函数,如果发现数组成员之间存在差异,该函数将返回 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;
}
新代码有什么问题?
I need to write a function that will return true if it has found a difference between members of an array.
My code is:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
I have to implement it with pointers.
The code above does not work(logically).
Can anybody help?
UPDATE:
I have changed my code to the following:
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;
}
What is the problem with the new code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对我来说就像是家庭作业,所以我不想破坏乐趣,但我想提一下关于 C 的一件事:指向某个数组的指针并不能告诉您有关数组大小的任何信息。因此,您的函数需要采用一个指针和第二个 size_t 参数(或者可能是指向数组最后一个元素的指针)。
This looks like homework to me, so I don't want to spoil the fun but one thing about C I'd like to mention: having a pointer to some array doesn't tell you anything about the size of the array. So your function will need to take a pointer and a second
size_t
argument (or maybe a pointer to the last element of the array).您的函数仅接受一个数组指针,这对于比较来说似乎太少了。
您必须添加一个指定数组长度的参数,或者实现某种“策略”,例如使用特定值终止数组。
您还应该考虑使用标准
memcmp()
函数。Your function only takes in a single array pointer, that seems like one too few for a comparison.
You must add an argument that specifies the lengths of the arrays, or implement some kind of "policy" that e.g. terminates the arrays using a specific value.
You should also look into using the standard
memcmp()
function.我不明白这个问题(不清楚你想要实现什么)...
正如其他人已经说过的,你的数组没有边界检查,这是错误的...
这是关于你的代码的一些其他反馈:
你的如果您显示了您期望返回什么返回值,则可以改进问题(以获得更有用的答案)。
基于此“我需要编写一个函数,如果发现数组成员之间存在差异,该函数将返回 true”。
在伪代码中,您似乎想要:
更新:
在您的新代码中...
这:
可能是:
如果您将函数末尾的
return 0
更改为return 1
I don't understand the question (It's unclear what you're trying to achieve)...
As others have already said, there's no boundary checking on your array, which is wrong...
Here's some other feedback on your code:
Your question could be improved (to get a more useful answer), if you showed what inputs you were expecting to return what return values.
Based on this 'I will need to write a function that will return true if its found diffrence between members of array.'
In pseudo code, it seems like you would want:
UPDATE:
In your new code...
This:
Could be:
If you changed the
return 0
at the end of your function toreturn 1