首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

malloc()总是可以增加数组的大小吗?

当然不是。malloc() 是 C 语言中用于动态分配内存的函数,它可以在运行时为程序分配所需的内存。然而,malloc() 不能直接用于增加数组的大小。

在 C 语言中,数组的大小是固定的,不能在运行时更改。如果需要动态调整数组大小,可以使用动态数组(例如,使用指针和 realloc() 函数)。realloc() 函数可以重新分配内存,并在需要时增加或减少分配的内存大小。

以下是使用 realloc() 动态调整数组大小的示例:

代码语言:c
复制
#include<stdio.h>
#include <stdlib.h>

int main() {
    int *arr = NULL;
    int n = 0, new_size, i;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    arr = (int *)malloc(n * sizeof(int));

    printf("Enter the elements of the array: ");
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter the new size of the array: ");
    scanf("%d", &new_size);

    arr = (int *)realloc(arr, new_size * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    printf("The new array is: ");
    for (i = 0; i < new_size; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);

    return 0;
}

请注意,realloc() 函数可能会失败并返回 NULL,因此在使用 realloc() 时要确保正确处理错误。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券