使用malloc过阵 [英] using malloc over array

查看:154
本文介绍了使用malloc过阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是SO发现了类似的问题。但是,我没有发现,这里是该方案

May be similar question found on SO. But, I didn't found that, here is the scenario

案例1

void main()
{
    char g[10];
    char a[10];
    scanf("%[^\n] %[^\n]",a,g);
    swap(a,g);
    printf("%s %s",a,g);
}

案例2

void main()
{
    char *g=malloc(sizeof(char)*10);
    char *a=malloc(sizeof(char)*10);
    scanf("%[^\n] %[^\n]",a,g);
    swap(a,g);
    printf("%s %s",a,g);
}

我得到在这两个情况下,相同的输出。所以,我的问题是,当我应该preFER 的malloc()而不是阵列或副诗句,为什么??我发现通用定义,的malloc()提供动态分配。所以,这是它们之间的唯一区别??请任何一个用例子来解释,什么是动的意思虽然我们指定的尺寸的malloc()

I'm getting same output in both case. So, my question is when should I prefer malloc() instead of array or vice-verse and why ?? I found common definition, malloc() provides dynamic allocation. So, it is the only difference between them ?? Please any one explain with example, what is the meaning of dynamic although we are specifying the size in malloc().

推荐答案

的原则性差别涉及何时以及如何决定数组​​长度。使用固定长度数组力量你决定在编译时的数组的长度。在使用的malloc对比让你在运行时决定数组的长度。

The principle difference relates to when and how you decide the array length. Using fixed length arrays forces you to decide your array length at compile time. In contrast using malloc allows you to decide the array length at runtime.

在特别是在运行时决定让你立足于用户输入的决定,在上编译的时候不知道的信息。例如,您可能会分配数组是一个规模足够大的用户,以适应实际输入的数据。如果使用固定长度的数组,你必须在编译时的上限来决定,然后强制这种限制到用户。

In particular, deciding at runtime allows you to base the decision on user input, on information not known at the time you compile. For example, you may allocate the array to be a size big enough to fit the actual data input by the user. If you use fixed length arrays, you have to decide at compile time an upper bound, and then force that limitation onto the user.

另外一个更微妙的问题是分配非常大的固定长度数组作为局部变量可能会导致堆栈溢出运行时错误。出于这个原因,你有时preFER分配这些阵列使用动态的malloc

Another more subtle issue is that allocating very large fixed length arrays as local variables can lead to stack overflow runtime errors. And for that reason, you sometimes prefer to allocate such arrays dynamically using malloc.

这篇关于使用malloc过阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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