使用malloc()初始化了5000字节的内存后,我该如何引用这 block 内存空间中的字节呢?例如,如果我需要指向内存中数据的起始位置,我该怎么做?
编辑:我用什么来指向它重要吗?我的意思是我看到人们使用 bytes/int/char?相关吗?
我得到的错误:
最佳答案
您可以使用下标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/