如何访问C中分配的内存?
使用malloc()初始化了5000字节的内存后,我该如何引用这块内存空间中的字节呢?例如,如果我需要指向内存中数据的起始位置,我该怎么做?
编辑:我用什么来指向它重要吗?我的意思是我看到人们使用 bytes/int/char?相关吗?
我得到的错误:
After using malloc() to initialize 5000 bytes of memory, how would I reference the bytes in this memory space? For example, if I need to point to a starting location of data within the memory, how would I go about that?
EDIT: Does it matter what I use to point to it? I mean I am seeing people use bytes/int/char? Is it relevant?
Error I get:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用下标 array[n] 运算符来访问您有兴趣读/写的索引,如下所示:
You can use the subscript
array[n]
operator to access the index you are interested in reading/writing, like so:Malloc 不会初始化它分配的位。请使用
calloc()
。Malloc doesn't initialize the bits allocated by it. Use
calloc()
rather.正如其他人所提到的,您可以执行以下操作:
但是,需要注意以下几点:
malloc
不会初始化内存,但calloc
会(如前所述)作者:Prasoon Saurav)As has been mentioned by others, you could do something like this:
However, a couple of things to note:
malloc
will not initialise the memory, butcalloc
will (as mentioned by Prasoon Saurav)malloc()
返回指向已分配内存的指针:malloc()
returns a pointer to the allocated memory:正如您所看到的 malloc 分配一个以字节为单位的内存块,您可以分配一个指向该块的指针,并且根据指针类型编译器知道如何引用单个元素:
现在如果您引用第二个元素短值,即
*(pshort + 1)
或pshort[1]
编译器知道它需要添加 2 个字节 (sizeof(short)
)以便获取下一个元素。现在,如果您引用第二个浮点值,即
*(pfloat + 1)
或pfloat[1]
编译器知道它需要添加 4 个字节 (sizeof( float)
) 以便获取下一个元素。与自己定义的数据类型相同:
pstruct + 1
在偏移量sizeof(mystruct_t)
处访问struct
,因此这实际上取决于您想要的方式使用分配的内存
as you have seen malloc allocates a block of memory counted in bytes, you can assign a pointer to that block and depending on the pointer type the compiler knows how to reference individual elements:
now if you reference the second short value i.e.
*(pshort + 1)
orpshort[1]
the compiler knows that it needs to add 2 bytes (sizeof(short)
) in order get the next element.now if you reference the second float value i.e.
*(pfloat + 1)
orpfloat[1]
the compiler knows that it needs to add 4 bytes (sizeof(float)
) in order get the next element.same with own defined data types:
pstruct + 1
accesses thestruct
at offsetsizeof(mystruct_t)
so it is really up to you how you want to use the allocated memory