c - 如何访问C中分配的内存?

标签 c data-structures

使用malloc()初始化了5000字节的内存后,我该如何引用这 block 内存空间中的字节呢?例如,如果我需要指向内存中数据的起始位置,我该怎么做?

编辑:我用什么来指向它重要吗?我的意思是我看到人们使用 bytes/int/char?相关吗?

我得到的错误: enter image description here

最佳答案

您可以使用下标array[n]运算符来访问您有兴趣读/写的索引,如下所示:

uint8_t* const bytes = (uint8_t*)malloc(5000);

bytes[0] = UINT8_MAX; // << write UINT8_MAX to the first element
uint8_t valueAtIndexZero = bytes[0]; // << read the first element (will be UINT8_MAX)
...
free(bytes), bytes = 0;

关于c - 如何访问C中分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109532/

相关文章:

c - Linux内核编译报错elf_x86_64 missing

c++ - 使开关繁重的功能更具可重用性

data-structures - MATLAB 中有 "queue"吗?

algorithm - 离散数学中的哪个主题被认为是数据结构类(class)的先决条件?

c - 解析一个缓冲区会影响另一个缓冲区吗?

c - 语法和指针运算

java - 小端到整数(或 BigInteger)

python - 实现一个带约束的 python 列表

c# - C#中的树数据结构

java - 在 Java 中使用数组实现堆栈