Reputation: 5
How do I allocate memory for 64 8-byte blocks? I've tried reading on uint64, but I'm not sure where to start.
Upvotes: 1
Views: 1811
Reputation: 786
You can do this just using malloc
:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main()
{
void* ptr = malloc(sizeof(uint64_t) * 64);
printf("Allocated memory begins at %p", ptr);
}
Upvotes: 1
Reputation: 6607
This should be very simple. Either run:
void *foo = malloc(64 * 8);
or, if you want type safety:
#if (CHAR_BIT != 8) #error Weird broken system, give up... #endif
uint64_t *foo = malloc(sizeof(uint64_t[64]));
Upvotes: 1
Reputation: 11809
In c, malloc
allocates the number of bytes specified, so if you want to allocate 64 8 bytes blocks then you must allocate malloc(64*8)
. Don't forget to free
them.
If you are not going to allocate them dinamically you can just declare an array. In c there's a type that have 64 bits (8 bytes) named uint64_t
, so you can declare an array of 64 elements of 8 bytes this way: uint64_t blocks[64]
.
As a reply of a question in your comments, declaring a variable will make it valid inside his scope. So if you declare the array globally, it will be valid until the program closes. And if you declare it inside an if
condition (for example), it will be valid only inside the conditional. Read this to understand better how it works: https://www.clear.rice.edu/elec201/ictutorial/tut2-4.html
If you allocate a piece of memory will malloc
, it's direction must be saved in a variable so you can access it later, and here applies the same scope rules, but don't forget to free
the memory before losing the direction pointer or you will have a memory leak.
If you don't have much experience I don't recommend using malloc
.
Upvotes: 1