动态数组和空指针
我有一个很奇怪的问题。我想初始化一个由 void 指针指向的数组,使用 new 向该数组分配内存,如下所示。
const int ARRAY_SIZE = 10;
void InitArray()
{
int *ptrInt = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
ptrInt[i] = 1; //OK
}
void *ptrVoid = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
*(int*)ptrVoid[i] = 1; //Culprit : I get a compiler error here
//(error C2036: 'void *' : unknown size)
}
}
现在,我想用 1 来初始化 ptrVoid
指向的这个数组的元素。我该怎么做呢?使用此代码,我收到编译器错误,如代码中所示(我使用的是 VS 2010)。有什么建议吗?
I have quite peculiar problem. I want initialize an array pointed by a void pointer to which memory is allocated using new as shown below.
const int ARRAY_SIZE = 10;
void InitArray()
{
int *ptrInt = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
ptrInt[i] = 1; //OK
}
void *ptrVoid = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE;i++)
{
*(int*)ptrVoid[i] = 1; //Culprit : I get a compiler error here
//(error C2036: 'void *' : unknown size)
}
}
Now, I want to initialize the elements of this array which is pointed by ptrVoid
with say 1. How do I go about it? With this code I get a compiler error as shown in the code(I am using VS 2010). Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您遇到了操作顺序问题(以及额外的
*
)。在第二个循环中尝试这个:You have an order of operations problem (and an extra
*
). Try this inside your second loop:*(int*)ptrVoid[i]
是*((int*)(ptrVoid[i]))
,并且您解除引用的次数太多([]
进行取消引用)。编写
((int*)ptrVoid)[i]
(或者更好的是,static_cast(ptrVoid)[i]
),然后重新考虑您的使用void*
根本就没有。*(int*)ptrVoid[i]
is*((int*)(ptrVoid[i]))
, and you're dereferencing too many times (the[]
does a dereference).Write
((int*)ptrVoid)[i]
(or, better,static_cast<int*>(ptrVoid)[i]
) then re-consider your use ofvoid*
at all.您只需正确加上括号并将
void*
转换为int*
,以便编译器知道当您使用[i 对其进行索引时要偏移多少字节]
。You just need to parenthesize correctly and cast the
void*
to anint*
, so that the compiler knows how many bytes to offset when you index it with[i]
.怎么样:
但是,人们必须想知道 void 数组或
1
初始化数据的含义是什么。这真的是一个 int 数组或其他类型的数组吗?它将作为 void* 传递,然后重新转换回类型数组?How about:
But, one has to wonder what the meaning of either a void array or
1
initialised data is. Is this really an array of int or some other type that is going to be passed as a void* and then recast back to a typed array?