【发布时间】:2020-04-12 08:34:58
【问题描述】:
我希望将此数组的长度作为用户的输入。
设 n 为输入的长度;
当我使用 malloc 时:int *arr1[n] = malloc((sizeof(int) * n) + 1);
它说无法初始化可变大小的数组,还有其他方法吗?
我想将一个数组作为用户的输入,对数组的元素进行排序并将排序后的元素存储在另一个数组中。这是我的完整代码:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int temp = 0;
temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int n = 0;
printf("Enter the number of elements - ");
scanf("%i", &n);
int *arr1[n];
int arr2[] = malloc((sizeof(int) * n) + 1);
printf("Enter the elements one by one - ");
for (int i = 0; i < n; i++)
{
scanf("%i", arr1[i]);
}
free(arr2);
}
我没有将第二个数组声明为 arr2[n],因为 n 是可变的,它不会让我用 malloc 初始化数组。有人可以帮我解决这个问题吗?
【问题讨论】:
-
int arr1[n] = malloc((sizeof(int) * n) + 1),为什么你把它做成区域 malloc 只是返回通用指针(指向 void 的指针)位置首地址在保留块中,所以只需使其 int *= (int)malloc((sizeof(int) * n) + 1);现在你有了一个数组!。
-
为什么是
+ 1?arr2是干什么用的?你根本不用它? -
确保您了解 scanf 中
%i和%d之间的区别 -
这里已经有人问过这个问题:stackoverflow.com/questions/6634888/…
标签: c arrays pointers memory malloc