malloc(sizeof(int))和malloc(sizeof(int *))有什么区别 [英] What is the difference between malloc(sizeof(int)) and malloc(sizeof(int*))

查看:99
本文介绍了malloc(sizeof(int))和malloc(sizeof(int *))有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为下面的2d int ptr分配内存,但是我不是100%正确地做到了正确的做法,因此任何关于此的指针(哈哈)都很好.我在for循环中释放数组及其索引的方式正确吗?另外,第一个 malloc 和第二个 malloc 有什么区别:(int *)(int)?

I'd like to allocate memory for the 2d int ptr below, but I'm not 100% positive I've done it correctly, so any pointers (ha ha) on that would be great. Is the way I free the array and its indexes in the for loop correct? Also, what is the difference between the first malloc and the second malloc: (int *) and (int)?

int **array = NULL;
int mem_size = 0;
int i = 0, j = 0;

// leaving out how mem_size is calculated, but it can vary

array = malloc(sizeof(int *) * mem_size);
if (array == NULL) {
    // some error message
    return;
}
for (i = 0; i < mem_size; i++) {
    array[i] = malloc(sizeof(int) * 2);
    if (!(array[i])) {
        // some error message
        for (j = 0; j < i; j++)
            free(array[j]);
        free (array);
        return;
    }
}

这只是我编写的代码的一部分.最后,我释放了数组:

This is only a section of the code I wrote. At the end, I am freeing the array:

for (i = 0; i < mem_size; i++)
   free(array[i]);

free(array);

推荐答案

它只是一个编译时间常数-第一种情况下指针的大小,第二种情况下int的大小.它可能因系统而异(例如,如果是针对32位系统进行编译,则指针将为4个字节,而在64位系统上则为8个字节).

It is just a compile time constant - size of pointer in first case, size of int in second. It may vary between systems (e.g. if compiling for 32bit systems, pointer would be 4 bytes, while on 64bit systems it is 8 bytes).

万一任何malloc在for循环中失败,我应该在那里释放数组

In case any of the mallocs fail in the for loop, should I be freeing the array there

您应该释放到目前为止分配的所有内容-每个 array [0 ..(i-1)] array 本身.

You should be freeing everything you've allocated so far - each array[0..(i-1)] and array itself.

malloc(sizeof(int *) * mem_size)

mem_size 指针数组分配内存.

malloc(sizeof(int) * 2);

为2个整数分配内存.

此外,您还应该考虑分配普通的1D数组,并且只在需要访问索引时才计算索引.

Also you should consider allocating ordinary 1D array and just calculating index when you want to access it.

这篇关于malloc(sizeof(int))和malloc(sizeof(int *))有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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