函数搜索数组成员之间的差异
问题描述:
我需要编写一个函数,如果它发现数组成员之间的差异将返回true。函数搜索数组成员之间的差异
我的代码是:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
我有一个指针来实现它。
上面的代码不起作用(逻辑上)。
任何人都可以帮忙吗?
UPDATE:
我已经改变了我的代码如下:
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的一件事我想提一提:有一个指向某个数组的指针并没有告诉你关于阵列。所以你的函数将需要一个指针和第二个参数(或者可能是指向数组的最后一个元素的指针)。
+1
是的。但是,一个重要的例外是C风格的字符串。 – 2011-05-25 07:55:27
答
我不明白的问题(目前还不清楚你想达到什么)......
正如其他人已经说过,没有边界的阵列,这是不对的检查...
这里是你的代码的一些其他反馈:
// 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
UPDATE:
在新的代码...
// You're still assuming the size of 'str'
int func1(int *str)
{
int i,temp=0;
// Loop while i < 9, i.e. 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 1
改变
return 0
这是功课? – 2011-05-25 07:50:34如果你更喜欢它,你可以使用数组符号:'str [i + 1]'和'*(str + i + 1)'在上面的代码中完全一样。 – pmg 2011-05-25 07:57:28
这是一个保证数组是否被排序以开始?如果不是,你需要比邻居多。 – pmg 2011-05-25 07:58:59