[英]outputting a value from a 2d array in a for loop in C
我正在尝试从 geeksforgeeks 解决这个问题: https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements/0我正在尝试 output 通过收集来自二维数组的输入值用户首先输出值,但我得到的是随机整数。 这些值出现在 for 循环之外就好了,这是我不理解的。 我用来旋转值的算法按我想要的方式工作。
这是我的代码:
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;
}
我还将展示我使用的算法,以防它可能对解决我的问题有用
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;
这是我在运行代码时收到的 output:
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
先感谢您:)
在results[i] = rotate_array(arr, N, D);
之后 , arr
消失,因此results[i]
不再有效。
{
...
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.
}
替代方案,分配数据
// int arr[N];
int *arr = malloc(sizeof *arr * N);
...
results[i] = rotate_array(arr, N, D);
然后释放它
for (int dj = 0; dj < arr_len[di]; dj++) {
printf("%d ", results[di][dj]);
}
printf("\n");
free(results[di]); // add
细节: int *results[T];
不是二维数组。 results
是一个指针数组。
“指针不是数组。数组不是指针。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.