'What is the purpose of the following function
This is my task. I googling for find out reason behind this function but can not find out. My teacher tell me what is the use of this function.
My Question is:
What is the purpose of the following function, assuming that the parameter
sizerepresents the size of the arraydatathat's also passed as a parameter. Further assume thatsizeis at least 2.
This is sample code he give me:
#include <stdio.h>
void procArray( int data[], int size ) {
int temp = data[0];
int index;
for( index = 0; index < size - 1; index++ )
{
data[index] = data[index + 1];
data[size-1] = temp;
printf("%d ", + data[index]);
printf("%d ", + data[size-1]);
}
}
int main()
{
int arr[2];
procArray(arr, 2);
return 0;
}
Every time i got random number in output like:
32767 -2102338448
Solution 1:[1]
The routine procArray appears to be written with the intent that it “rotate” the array one position “left,” meaning to modify the array such that, upon return from the function:
- The last element (index
[size-1]) contains the value the first element (index[0]) the first element had upon calling the function. - Each other element (index
[i]for someiother thansize-1) contains the value the element to its “right” (index[i+1]) had upon calling the function.
However, if this was the purpose, the function was written incorrectly. The statement data[size-1] = temp; should be after the loop, not inside it.
Further, the main routine fails to demonstrate how the function behaves because it fails to put values into arr.
A corrected function with a useful demonstration is:
#include <stdio.h>
#include <stdlib.h>
void procArray(int data[], size_t size)
{
int temp = data[0];
for (size_t i = 0; i < size-1; ++i)
data[i] = data[i+1];
data[size-1] = temp;
}
int main(void)
{
int arr[5] = {10, 11, 12, 13, 14};
procArray(arr, 5);
for (int i = 0; i < 5; ++i)
printf("arr[%d] = %d.\n", i, arr[i]);
return 0;
}
This program outputs:
arr[0] = 11. arr[1] = 12. arr[2] = 13. arr[3] = 14. arr[4] = 10.
Solution 2:[2]
It's because you array is not initialized.
In C, when you write int arr[2] your array is initialized with random value.
Your array doesn't have data in it, so the compiler doesn't know and set a random value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jabberwocky |
