简体   繁体   中英

Allocating memory for 64 8-byte blocks

How do I allocate memory for 64 8-byte blocks? I've tried reading on uint64, but I'm not sure where to start.

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]));

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 .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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