【问题标题】:How is memory properly allocated?如何正确分配内存?
【发布时间】:2020-05-30 18:37:58
【问题描述】:

所以我正在学习并试图弄清楚 c 中的内存分配,在这段代码中,内存分配是否正确?我是否也需要分配数组,还是因为用户输入的所有内容都进入数组(将存储在数组中)而导致数组已经分配?

#include <stdio.h>
#include <stdlib.h>
int main() {
    int i;
    int arr[20];
    int b;
    int *ptr;
    ptr = &b;

    ptr = (int*) malloc(20 *sizeof(int));

    //find largest element in array
    printf("Enter the number of elements: ");
    scanf("%d", &b);
    if(ptr == NULL)
    {
        printf(" No memory allocated.");
        exit(0);
    }


    for (i = 0; i < b; ++i) {
        printf("Enter number%d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    for (i = 1; i < b; ++i) {
        if (arr[0] < arr[i])
            arr[0] = arr[i];
    }
    free(ptr);
    printf("Largest element = %d", arr[0]);


    return 0;
}

【问题讨论】:

  • 您分配内存但不使用它。 arr 和 ptr 没有任何关系

标签: c memory memory-management


【解决方案1】:

你可以清理malloc调用:

ptr = malloc( 20 * sizeof *ptr );

你不需要转换malloc 的结果,除非你使用ancient pre-C89 实现或C++(在这种情况下你应该使用new/delete 而不是malloc/free,或者更优选是容器类型,例如vector)。

sizeof *ptr 在这种情况下等同于sizeof (int)

但是,您实际上并没有使用该内存 - 您分配并释放它,但您从未向其写入任何内容。

您最初将&amp;b 分配给ptr,但随后您使用malloc 调用的结果覆盖它,因此如果您希望该内存以某种方式附加到b,请注意它不是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2021-03-18
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多