什么是使用malloc时可以使用指针的呢? [英] What's the point of using malloc when you can use pointer?

查看:346
本文介绍了什么是使用malloc时可以使用指针的呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不能,只要你想使用指针,你只储存尽可能多的数据?
为什么你必须使用的malloc()来获得更多的内存?

 为int *一个;
INT MAX,我;
的printf(请输入你想要的最大数:);
scanf函数(%d个,&安培;最大);对于(i = 0; I<最大;我++)
{
    *(A + I)= I;
}对于(i = 0; I<最大;我++)
{
    的printf(%d个\\ N,*(A + I));
}
返回0;

所以我让用户选择的任何号码,电脑将分配内存吧?代替使用以下code:

  A =(INT *)malloc的(10 * sizeof的(INT));


解决方案

在您的code,

  *(A + I)= I;

是错误的,因为你想写入未初始化的内存。这反过来又调用未定义行为

要详细说明,只是定义一个指针不自动分配的无限的访问内存的指针。你需要的添加的在指针将是位置的指向的。当你简单地定义一个指针(本地),它指向一些的未知的内存位置这是最有可能既不合法,也不通过访问你的程序。所以,当您尝试访问内存位置,它本质上是一些访问的无效的内存。这是UB。

因此​​,


  

你为什么要使用malloc获得更多的内存?


的malloc()不是用来获得的更多的内存,而这是给在要求内存位置访问。


编辑:

关于你的编辑,

  A =(INT *)malloc的(10 * sizeof的(INT));

两件事情加,


  1. 明白为什么不能投 的返回值的malloc()和家人在 C

  2. 经常检查的()成功的malloc 使用前返回的指针。

Can't you just store as much data as you want using pointer? Why do you have to use malloc() to gain more memory?

int * a;
int max, i;
printf("Enter the maximum number you want: ");
scanf("%d", &max);

for (i = 0; i < max; i++)
{
    * (a + i) = i;
}

for (i = 0; i < max; i++)
{
    printf("%d\n", * (a + i));
}
return 0;

so I let the user choose whatever number, and computer will 'allocate the memory' right? instead of using the following code:

a = (int *) malloc(10 * sizeof(int));

解决方案

In your code,

  * (a + i) = i;

is wrong, because you're trying to write into uninitialized memory. This in turn invokes undefined behaviour.

To elaborate, just defining a pointer does not automatically allocate limitless accessible memory to that pointer. You need to add the location where the pointer will be pointing to. When you simply define a pointer (local), it points to some unknown memory location which is most likely neither valid nor accessible by your program. So, when you try to access that memory location, it is essentially accessing some invalid memory. This is UB.

So,

Why do you have to use malloc to gain more memory?

malloc() is not used to gain more memory, rather it is giving the required memory location to be accessed.


EDIT:

Regarding your edit,

 a = (int *) malloc(10 * sizeof(int));

two things to add,

  1. Please see why not to cast the return value of malloc() and family in C.
  2. Always check for the success of malloc() before using the returned pointer.

这篇关于什么是使用malloc时可以使用指针的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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