[英]Dynamic memory and pointers
我正在编写一个必须为某种类型的内存分配的程序,它必须存储数据的大小以及我传递给它的数据的大小。 因此,如果我分配8个字节,则需要在前4个字节中存储内存大小,并在其他4个字节中存储剩余大小。 我认为这是带有标头的,但我对C还是很陌生。我现在所拥有的只是分配的空间,如何在其中存储值?
int * mem_start_ptr; //pointer to start off memory block
int data;
data = &mem_start_ptr;
mem_start_ptr = (long *)malloc(sizeof(long)); //reserver 8 bytes
首先, sizof(long)
是特定于实现的,在64位Linux上为8字节,在Windows和32位Linux(AFAIK)上为4字节。 如果要显式分配8个字节,请使用malloc(8)
。 虽然,由于您想存储int
,所以似乎可以使用malloc(sizeof(*mem_start_ptr))
。 另外,不要malloc
的返回值,它在C语言中是多余的,甚至可以隐藏bug。 现在,要存储这两个4字节值:
/* for the first one. Let's use 42 */
*mem_start_ptr = 42;
/* for the second one. Let's put the value of of some variable here */
*(mem_start_ptr + 1) = int_variable;
您应该阅读有关指针算术的知识。 也可能关于数组。 Google是您的朋友。 另外,不知道您的代码中的该部分是做什么用的。 由于它没有执行您可能期望的操作 :
int data;
data = &mem_start_ptr
最后,我将像这样重写您的代码:
int *mem_start_ptr;
mem_start_ptr = malloc(sizeof(*mem_start_ptr));
*mem_start_ptr = your_1st_4bytes;
*(mem_start_ptr + 1) = your_2nd_4bytes;
在不再需要它之后,别忘了对其进行free()
。 另外,我没有在这里开枪,但也不要忘记检查NULL
,因为malloc()
会在失败时返回该值。
再说一遍-了解指针算法。 Google是您的朋友;]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.