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
size
represents the size of the arraydata
that's also passed as a parameter. Further assume thatsize
is 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
CodePudding user response:
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 somei
other 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.
CodePudding user response:
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.