[英]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.