Reputation: 45
I am trying to solve this problem from geeksforgeeks: https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements/0 I am trying to output values from a 2d array by collecting all the input from the user first then outputting the values, but I am getting random integers instead. The values appear outside the for loop just fine which is what I am not understanding. The algorithm I use to rotate the values works the way I want it to.
Here is my code:
int * rotate_array(int *array, int max_size, int rotate_by_D);
int main()
{
//First accept and store all inputs
int T, N, D;
scanf("%d", &T);
int arr_len[T];
int *results[T];
for (int i = 0; i < T; i++)
{
scanf("%d %d", &N, &D);
int arr[N];
arr_len[i] = N;
//store each length of the array
for (int j = 0; j < N; j++)
{
int user_input;
scanf("%d", &user_input);
arr[j] = user_input;
}
results[i] = rotate_array(arr, N, D);
}
//I can get the value I anticipate here
printf("%d\n", results[0][0]);
//the code below is where i am trying to output the new values to the users
//But I see random numbers instead
for (int di = 0; di < T; di++)
{
for (int dj = 0; dj < arr_len[di]; dj++)
{
printf("%d ", results[di][dj]);
}
printf("\n");
}
return 0;
}
I will also display the algorithm I have used just in case it may be useful in solving my problem
int * rotate_array(int *array, int max_size, int rotate_by_D)
{
int original_value[max_size];
for (int k = 0; k < max_size; k++)
{
original_value[k] = array[k];
if ((k + rotate_by_D) >= max_size)
{
int new_pos = (k + rotate_by_D) % max_size;
array[k] = original_value[new_pos];
}
else
{
array[k] = array[k + rotate_by_D];
}
}
return array;
Here is the output I receive when I run my code:
1 (The number of test cases)
3 2 (The array size and how much to rotate them by respectively)
1 2 3 (the array of values)
output
3 (This is from outside the loop)
-494200848 32766 221572309 (This what I get inside of the loop)
I expect the value to be: 3 1 2
Thank you in advance :)
Upvotes: 1
Views: 37
Reputation: 153498
Right after results[i] = rotate_array(arr, N, D);
, arr
goes away and so results[i]
is no longer valid.
{
...
int arr[N];
...
results[i] = rotate_array(arr, N, D);
... // arr[] is no longer valid at the close of this block.
// Since rotate_array() returns `arr`, results[i] like-wise becomes invalid.
}
Alternative, allocate data
// int arr[N];
int *arr = malloc(sizeof *arr * N);
...
results[i] = rotate_array(arr, N, D);
And later free it
for (int dj = 0; dj < arr_len[di]; dj++) {
printf("%d ", results[di][dj]);
}
printf("\n");
free(results[di]); // add
Detail: int *results[T];
is not a 2D array. results
is an array of pointers.
"A pointer is not an array. An array is not a pointer."
Upvotes: 1