int findVal (int *array, int size, int val) {
for (int i = 0; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
为允许您指定起点(或者更准确地说,比起点少一)的函数:
int findVal (int *array, int size, int last, int val) {
for (int i = last + 1; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
然后让您的客户使用以下方式调用它:
int index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), -1, myval);
while (index != -1) {
// Do something with index.
index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), index, myval);
}
You could go to the trouble of allocating a dynamic array within the function but that's probably something better left to the caller to manage.
I would change the function from something like:
int findVal (int *array, int size, int val) {
for (int i = 0; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
to one that allowed you to specify a starting point (or, more precisely, one less than the starting point):
int findVal (int *array, int size, int last, int val) {
for (int i = last + 1; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
then let your client call it with:
int index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), -1, myval);
while (index != -1) {
// Do something with index.
index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), index, myval);
}
If your client wants it in an array, they can put it in an array. But, if they just want to do something ephemeral (like just print the index then forget about it), it makes little sense to waste an array for that.
Instead of returning matching elements, you could print out their index values (allowing multiple values to be printed) or insert them into an array and then return that.
发布评论
评论(2)
您可能会遇到在函数内分配动态数组的麻烦,但这可能更好地留给调用者来管理。
我会将函数从类似以下内容更改
为允许您指定起点(或者更准确地说,比起点少一)的函数:
然后让您的客户使用以下方式调用它:
如果您的客户希望将其放在数组中,他们可以将其放入数组中。但是,如果他们只想做一些短暂的事情(比如只打印索引然后忘记它),那么为此浪费一个数组就没有意义了。
You could go to the trouble of allocating a dynamic array within the function but that's probably something better left to the caller to manage.
I would change the function from something like:
to one that allowed you to specify a starting point (or, more precisely, one less than the starting point):
then let your client call it with:
If your client wants it in an array, they can put it in an array. But, if they just want to do something ephemeral (like just print the index then forget about it), it makes little sense to waste an array for that.
您可以打印出它们的索引值(允许打印多个值)或将它们插入到数组中然后返回,而不是返回匹配的元素。
Instead of returning matching elements, you could print out their index values (allowing multiple values to be printed) or insert them into an array and then return that.