为什么C数组需要,如果有指针? [英] Why does C need arrays if it has pointers?

查看:109
本文介绍了为什么C数组需要,如果有指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们可以使用指针和的malloc 以创建和使用数组,为什么数组类型中存在C?是不是很不必要的,如果我们可以用指针来代替?

If we can use pointers and malloc to create and use arrays, why does the array type exist in C? Isn't it unnecessary if we can use pointers instead?

推荐答案

数组是比动态内存分配速度更快。

Arrays are faster than dynamic memory allocation.

数组被分配在编译时,而在运行时的malloc进行分配。清分需要时间的。

Arrays are "allocated" at "compile time" whereas malloc allocates at run time. Allocating takes time.

此外,C并不要求的malloc()和朋友都在独立的实现提供。

Also, C does not mandate that malloc() and friends are available in free-standing implementations.


修改

阵列示例

#define DECK_SIZE 52
int main(void) {
    int deck[DECK_SIZE];
    play(deck, DECK_SIZE);
    return 0;
}

示例的malloc()

int main(void) {
    size_t len = 52;
    int *deck = malloc(len * sizeof *deck);
    if (deck) {
        play(deck, len);
    }
    free(deck);
    return 0;
}

在该阵列版本,对于甲板阵列内的空间由编译器保留在创建程序时(但是,当然,存储器仅保留/占用当程序正在运行),在的malloc()版本,为甲板空间阵列已被要求在程序的每次运行。

In the array version, the space for the deck array was reserved by the compiler when the program was created (but, of course, the memory is only reserved/occupied when the program is being run), in the malloc() version, space for the deck array has to be requested at every run of the program.

阵列永远不能改变大小,在需要的时候malloc分配的内存可以成长。

Arrays can never change size, malloc'd memory can grow when needed.

如果你只需要元素的固定数量,使用数组(你实现的范围内)。
如果你需要内存可以在程序运行过程中放大或缩小,使用的malloc()和朋友。

If you only need a fixed number of elements, use an array (within the limits of your implementation). If you need memory that can grow or shrink during the running of the program, use malloc() and friends.

这篇关于为什么C数组需要,如果有指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆