English 中文(简体)
将记忆分配给点C++
原标题:Allocating memory and assigning it to pointer C++
  • 时间:2012-05-18 11:51:02
  •  标签:
  • c++
  • pointers

如果我这样做,那是什么样的区别。

  int *i = new int;
  *i = 5;
  *(i+1) = 20;

以及

  int *i2 = new int [2];
  i2[0] = 5;
  i2[1] = 20;

I can access 以及use these 2 pointers the same way but what is the difference between these 2 examples 以及what errors can occur if I don t allocate enough memory, as in the first example?

最佳回答

差异是第一种援引未界定的行为。 任何事情都会发生,包括方案故障,或数据腐败,甚至只是“工作”。

问题回答

第一种选择是写上已经分配的记忆。 这可能导致不可预测的行为,如坠毁。

首先,我们为一名愤怒者分配了记忆。 因此,我们无法做到*(i+1),这样一来,我们就将搬到没有界定行为的下一个地点,即可能立即或稍后坠毁。

在后来的案例中,我们为两名愤怒者分配了记忆。

最可能的事情是数据腐败,但一般而言,数据腐败没有界定。

你掌握的内容没有任何差别。 The syntax *(i+1) (pointer notation) and i*** (array elements access notation) are the same. 在这种情况下,你可以认为一个点子和一个等数阵列(有两种方式使用同一要素)

正如其他人提到的那样,如果你(从业者)获得尚未适当分配的记忆,你将不明确行为。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签