【问题标题】:allocating memory to an array of variable length将内存分配给可变长度的数组
【发布时间】: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);现在你有了一个数组!。
  • 为什么是 + 1arr2 是干什么用的?你根本不用它?
  • 确保您了解 scanf 中 %i%d 之间的区别
  • 这里已经有人问过这个问题:stackoverflow.com/questions/6634888/…

标签: c arrays pointers memory malloc


【解决方案1】:

没有其他方法可以做到,但是有一个正确的方法:

你想要这个:

int arr1[n];
int *arr2 = malloc((sizeof(int) * n) + 1);
...
scanf("%i", &arr1[i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-18
    • 2013-05-16
    • 2020-09-06
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    相关资源
    最近更新 更多