动态内存和指针

时间:2013-02-04 23:05:01

标签: c pointers memory header malloc

我正在制作一个必须为某种类型分配内存的程序,它必须存储数据的大小以及传递给它的数据的大小。因此,如果我分配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

1 个答案:

答案 0 :(得分:0)

首先,sizof(long)是特定于实现的,在64位Linux上是8字节,在Windows和32位Linux,AFAIK上是4字节。如果要显式分配8个字节,请使用malloc(8)。虽然,因为您想要存储int,但似乎使用malloc(sizeof(*mem_start_ptr))。另外,不要转换malloc的返回值,它在C中是多余的,甚至可以隐藏错误。 现在,要存储这两个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;

您应该阅读指针算法。也可能是阵列。谷歌是你的朋友。此外,不知道您的代码中的这一部分是什么。 因为它没有做你可能期望的事情

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()会在失败时返回。

再一次 - 阅读指针算术。谷歌是你的朋友;]

相关问题