[英]Referencing a variable allocated in heap
I recently picked up C but am a little confused about how we reference something allocated in the heap.我最近拿起了 C 但对我们如何引用堆中分配的东西有点困惑。
For example, assume we did something as follows:例如,假设我们做了如下的事情:
void test(){
int *a;
a = (int*)(malloc(sizeof(int)*4));
a[0] = 1;
a[1] = 2;
a[2] = 0;
a[3] = 0;
}
Now, let's say I am in main, obviously, I cannot do something like a[0]=...
outside the function as there is no reference to a
, but it is allocated in the heap, so how would I make a reference to it?现在,假设我在 main 中,显然,我不能在 function 之外做类似
a[0]=...
之类的事情,因为没有对a
引用,但它是在堆中分配的,所以我将如何引用给它? I am guessing I'd have to return an int*
or store the address to a
outside the function.我猜我必须返回一个
int*
或将地址存储到a
之外。
I am guessing I'd have to return an
int*
or store the address toa
outside the function.我猜我必须返回一个
int*
或将地址存储到a
之外。
Yes, that is exactly how it works.是的,这正是它的工作原理。
malloc
allocates a block of memory for you and returns a pointer to the first byte of that memory block. malloc
为您分配一块 memory 并返回指向该 memory 块的第一个字节的指针。
You must make sure to always keep a pointer to the memory block until you call free
on it.您必须确保始终保留指向 memory 块的指针,直到您对其进行
free
调用。
This can be done by either returning a pointer to it from the function:这可以通过从 function 返回指向它的指针来完成:
int* test(void){
int *a;
a = (int*)(malloc(sizeof(int)*4));
//... (Also check here that malloc didn't return NULL.)
return a;
}
or by storing it somewhere else, eg an out-parameter passed to the function or a global variable.或将其存储在其他地方,例如传递给 function 或全局变量的输出参数。
If you leave the function without storing or returning a copy of the pointer anywhere, then you loose the last pointer to the memory block ( a
) and there will be no way to ever reach it again.如果您离开 function 而不在任何地方存储或返回指针的副本,那么您将丢失指向 memory 块 (
a
) 的最后一个指针,并且将无法再次到达它。
This latter situation is known as a memory leak .后一种情况称为memory 泄漏。
store the address to
a
将地址存储
a
It should be the address held by a
, not the address of a
.它应该是
a
持有的地址,而不是a
的地址。 a
's value is the address of the allocated memory's first byte. a
的值是分配的内存的第一个字节的地址。 The address of a
is the address of the pointer variable itself. a
的地址是指针变量本身的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.