English 中文(简体)
在 C++ 中将数组变量指定为同一数据类型的指针
原标题:Assigning an array variable to a pointer of same data type in C++

在下面的 C++ 片段中, a=b 可能缩放吗??

unsigned int * a;
D3DCOLOR b[16];
a=(unsigned int)b;

此任务是否将 b 数组的所有元素复制为 a? 类型是否正常?

最佳回答

首先,它应该是:

a = (unsigned int *)b; // note the *

更重要的是,这只使 a 指向 b 的 < em> 内容, 它确实 < enger > not 复制它。 如果您想要复制数组, 您必须明确地这样做, 例如使用 环或 std:: copy , 也就是说, 如果您不想使用类和材料 。

旁注: 要复制到 a , 您需要内存 a ! 您可以在堆栈上做 :

unsigned int a[16]; // 16 is an example

或动态的(例如 new )。

问题回答

Your code will not work, with a pointer you get access to the same memory as the object you point it to. What do you want to do, exactly? From your code, I d guess that the array you have is a bit array and you want the corresponding unsigned integer. In that case, do something like this:

unsigned int a;
unsigned int length = 16;
D3DCOLOR b[length];
for(int i = 0; i < length; i++)
{
  a |=  b[(length-1) - i] << i;
}

这将需要每个位元, 以所需的数量将其转换为所需的数量, 然后将其写入 a。 如果您想知道更多, 请查看 c/ c++ 中的位元操作 。

(注:本代码假定为大连位顺序)。





相关问题
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?