简体   繁体   English

动态内存和指针

[英]Dynamic memory and pointers

I'm making a program that has to allocate memory for a certain type and it has to store the size of the data and also the size of the data I passed to it. 我正在编写一个必须为某种类型的内存分配的程序,它必须存储数据的大小以及我传递给它的数据的大小。 So if I allocate 8 bytes I need to store the size of memory in the first 4 bytes and store the remaining size in the other 4 bytes. 因此,如果我分配8个字节,则需要在前4个字节中存储内存大小,并在其他4个字节中存储剩余大小。 I think this is referred to has headers, but I'm still fairly new to C. All I have right now is the allocated space, how do I store values in that? 我认为这是带有标头的,但我对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

First of all, sizof(long) is implementation specific and is 8 bytes on 64bit Linux, yet 4 bytes on Windows and 32bit Linux, AFAIK. 首先, sizof(long)是特定于实现的,在64位Linux上为8字节,在Windows和32位Linux(AFAIK)上为4字节。 Use malloc(8) if You want to allocate 8 bytes explicitly. 如果要显式分配8个字节,请使用malloc(8) Although, since You want to store int , it seems, use malloc(sizeof(*mem_start_ptr)) . 虽然,由于您想存储int ,所以似乎可以使用malloc(sizeof(*mem_start_ptr)) Also, don't cast the return value of malloc , it is redundant in C and can even hide bugs. 另外,不要malloc的返回值,它在C语言中是多余的,甚至可以隐藏bug。 Now, to store those two 4 byte values: 现在,要存储这两个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;

You should read about pointer arithmetic. 您应该阅读有关指针算术的知识。 And also probably about arrays. 也可能关于数组。 Google is Your friend. Google是您的朋友。 Also, no idea what this part in Your code is for. 另外,不知道您的代码中的该部分是做什么用的。 As it does not do what You probably expect it to do : 由于它没有执行您可能期望的操作

int data;
data = &mem_start_ptr

In the end, I'd rewrite Your code like this: 最后,我将像这样重写您的代码:

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;

Don't forget to free() it after it is no longer needed. 在不再需要它之后,别忘了对其进行free() Also, I did not shot it here, but also don't forget to check for NULL , as malloc() returns that on failure. 另外,我没有在这里开枪,但也不要忘记检查NULL ,因为malloc()会在失败时返回该值。

Yet again - read about pointer arithmetics. 再说一遍-了解指针算法。 Google is Your friend ;] Google是您的朋友;]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM