如果找到数组成员之间的差异,我需要编写一个返回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;
}
新代码有什么问题?
答案 0 :(得分:2)
这看起来像我的作业,所以我不想破坏乐趣,但有一点关于C我想提一下:有一个指向某个数组的指针并没有告诉你关于数组大小的任何信息。所以你的函数需要一个指针和第二个size_t
参数(或者是一个指向数组最后一个元素的指针)。
答案 1 :(得分:2)
答案 2 :(得分:0)
我不明白这个问题(目前还不清楚你想要达到的目标)......
正如其他人已经说过的那样,你的阵列没有边界检查,这是错误的......
以下是您的代码的其他一些反馈:
// 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, 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 0
更改为return 1