Originally Posted by
ymc1g11
say i have an array of length 20 passed into my function. but then I wanted my function to return the location of, say, from index 4 to 12.
Is it even possible to do it without passing one more argument?
An array is only fully specified if it has a starting point and a length. So if you change the length you need to provide it back to the caller. Revise your function to also return the new size>
Code:
void myfunction(int *array, int size, int *outArray, int *outSize)
{
for (int i=0; i < size; i++)
if (array[i] >= 0) {
outArray = &array[i];
*outSize = size-i;
return;
}
outArray = NULL;
*outSize = 0;
return;
}
Test case
Code:
#define NELEMS(x) (sizeof (x) / sizeof (x[0]))
int main()
{
int oldData[] = {-1, -1, -1, -1, -1, 3, 2, 3, 4, 5, 6, 7, 8, 2};
int newData[NELEMS(oldData)];
int newSize;
myfunction(oldData, NELEMS(oldData), newData, &newSize);
printf("Old data starts at %p and is %d elements long\n",
oldData, NELEMS(oldData));
printf("New data starts at %p and is %d elements long\n",
newData, newSize);
return 0;
}