初學者在這裏。是否有可能得到一個緩衝,例如:從緩衝區分配不同的內存塊
char buffer[1024];
它分割成更小的內存塊(根據用戶輸入任意大小)使用malloc,直到有緩衝區沒有更多的空間?例如:第一個塊= 16,第二個塊= 256,第三個塊= 32等等,直到我達到1024.另外我想爲每個創建的塊創建一個結構。我使用的是普通的C.
雖然我不知道如果我能做到這一點,我已經開始了一句:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int x = 0;
printf("Enter size of block to be allocated: ");
scanf("%d", &x);
/*(need to implement): call the following function until there's no more
space left in the buffer*/
allocate(x);
return 0;
}
void *allocate(size_t size)
{
char buffer[1024];
char *block;
/*The following allocates a block with the size of the user input.
How do I associate it with the buffer?*/
block = (char *) malloc(size + 1);
//Creates a structure. How do I create one for every block created?
typedef struct blk_struct
{
int data;
struct blk_struct *size_blk;
struct blk_struct *next;
}blk_struct;
blk_struct *first;
}
研究我做:谷歌和SO。兩者都找不到任何東西。也許我不是在尋找正確的關鍵詞? 在此先感謝。
的malloc已經在做這樣的事情在內部說(如果我沒有完全誤解了你的問題) – UmNyobe