int指针如何存储多个int [英] How can a int pointer stores more than one int

查看:89
本文介绍了int指针如何存储多个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


这可能是一个小问题,但对我来说很不利。我把我的想法放在下面的评论中。


我的想法是,如果我为一个int分配内存,我怎么能存储10个int元素。这种类型的存储元素是否安全。


Hi all,

This might be a small query but imp for me. I have put my ideas in comments in below prog.

My idea is if i am assigning memory for one int how can i store there 10 elements of int. Is this type of storing elements is safe.



展开 | 选择 | Wrap | 行号

推荐答案

不,它不安全。您只为一个整数分配内存,但是您在有效分配的地址的下一个9个整数位置存储了9个以上的值。

它可能导致分段错误。你无法预测它。理想情况下它们是无效的。

亲切的问候。

Aftab
No, its not safe. You are allocating memory for only one integer, but you are storing 9 more values at next 9 integer locations from valid allocated address.
It may cause Segmentation Fault. You can''t predict about it. Ideally they are invalid.
Kind Regards.
Aftab


感谢您的回复。但我经常看到这种类型的代码通过一些proggramres(他们是一些exp人:))。同样地,我们可以仅为一个char激活char *但可以存储多个值。我自己看到他们工作了几千字节。但这并不是为什么这一点是允许的。


我需要你们在这个话题上多说一些话......一些阐述会非常令人沮丧...... />


谢谢
Thanks for ur reply. But i have seen often this typeof code wriiten by some proggramres(they are some exp people :)). and also same way we can delare a char* for only one char but can store more than one value . I myself seen they are working for some thousands byte. But don''t why this is allowed at all.

I need some more words from u guys on this topic.....some elaboration will highly apreciated...


Thanks


处理未分配的内存肯定是危险的。您无法预测何时会出现Segmentation Fault。它有时可能会起作用,因为操作系统会在块中分配内存以提高效率。虽然你只想要4个字节,但它可能会给你更多(例如512字节块)。因此,在使用4个字节后,您的程序仍有一些未使用的内存。所以,它不会显示错误。但正如我所说,它不可预测,应该避免。安全处理内存是一种很好的编程习惯。

亲切的问候,

Aftab
It''s certainly dangerous to work on unallocated memory. You can''t predict when there will be Segmentation Fault. It may work sometimes because OS allocates memory in blocks for increasing efficiency. Though you want only 4 bytes, it may give you more (e.g. 512 bytes block). So your program still have some memory left as unused after using your 4 bytes. So, it will not show you error. But as I said its unpredictable and should be avoided. Handling memory safely is a good programming practice.
Kind Regards,
Aftab


这篇关于int指针如何存储多个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆