内存分配的问题 [英] Memory Allocation Problem
问题描述
这个问题被问了写轮面试的:
This question was asked in the written round of a job interview:
#include<alloc.h>
#define MAXROW 3
#define MAXCOL 4
main()
{
int (*p)[MAXCOL];
p = (int (*)[MAXCOL]) malloc(MAXROW*(sizeof(*p)));
}
多少字节的过程中被分配?
How many bytes are allocated in the process?
说实话,我并没有回答这个问题。我不明白分配到 P
。
To be honest, I did not answer the question. I did not understand the assignment to p
.
谁能给我解释一下什么是答案,以及如何推导?
Can anybody explain me what would be the answer and how it can be deduced?
推荐答案
这是依赖于平台。
INT(* P)MAXCOL];
声明了一个指向整数数组元素MAXCOL宽(当然是MAXCOL 4在这种情况下)。因此,这个指针的一个元素是 4 * sizeof的(INT)
目标平台上。
int (*p)[MAXCOL];
declares an pointer to an array of integers MAXCOL elements wide (MAXCOL of course is 4 in this case). One element of this pointer is therefore 4*sizeof(int)
on the target platform.
的的malloc
语句分配的内存缓冲区的MaxRow时间包含在P.因此,类型,总共的MaxRow规模* MAXCOL整数分配。字节的实际数量将取决于目标平台上。
The malloc
statement allocates a memory buffer MAXROW times the size of the type contained in P. Therefore, in total, MAXROW*MAXCOL integers are allocated. The actual number of bytes will depend on the target platform.
此外,还有C运行时使用的可能是更多的内存(如malloc的内部bookeeping,以及前主
被称为其中发生的各种进程初始化位),这也完全依赖于平台。
Also, there's probably additional memory used by the C runtime (as internal bookeeping in malloc, as well as the various process initialization bits which happen before main
is called), which is also completely platform dependant.
这篇关于内存分配的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!