C 控制台游戏的动态大小输入缓冲区
嘿,我正在尝试用 C++ 重写代码以在 C 中工作。我基本上只是想在 C 中找到 new 和 delete 的等效项,但它不太工作,这是我的代码:
这是 C++ 中的代码:
// Gets the number of events
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
// Sizes the eventbuffer based on the number of events
INPUT_RECORD *eventBuffer = new INPUT_RECORD[numEvents];
// Removes from memory:
delete[] eventBuffer;
这是什么到目前为止,我在 C:
// Event buffer
INPUT_RECORD *eventBuffer;
// Gets the number of events
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
// Sizes the event buffer based on the number of events.
eventBuffer = malloc(numOfEvents * sizeof(*eventBuffer));
// Removes from memory:
free(eventBuffer);
上面的代码几乎可以运行,但有一个错误: 错误:“void *”类型的值无法分配给“INPUT_RECORD *”类型的实体
Hey, I'm trying rewrite code in C++ to work in C. I'm basically just trying to find an equivalent for new and delete in C but it's not quite working, here is my code:
Here's the code in C++:
// Gets the number of events
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
// Sizes the eventbuffer based on the number of events
INPUT_RECORD *eventBuffer = new INPUT_RECORD[numEvents];
// Removes from memory:
delete[] eventBuffer;
Here's what I have so far in C:
// Event buffer
INPUT_RECORD *eventBuffer;
// Gets the number of events
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
// Sizes the event buffer based on the number of events.
eventBuffer = malloc(numOfEvents * sizeof(*eventBuffer));
// Removes from memory:
free(eventBuffer);
The code above almost works with one error:
Error: a value of type "void *" cannot be assigned to an entity of type "INPUT_RECORD *"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你只需要强制转换它——
当然,有人会说标准规定你不必强制转换“malloc”的结果。显然,在这种情况下,标准是无关紧要的:)
You just have to cast it --
Of course, someone is going to come along and say that the standard says you don't have to cast the result of "malloc". Obviously, in this case, the standard is irrelevant :)
你的C++代码不起作用。您将
eventBuffer
传递给ReadConsoleInput()
,但直到稍后才声明它:如果
ReadConsoleInput()
需要eventBuffer
对于某些东西,您需要在调用函数之前声明它。不管怎样,等效的 C 代码是:
Your C++ code doesn't work. You pass
eventBuffer
toReadConsoleInput()
but it's only later that you declare it:If
ReadConsoleInput()
needseventBuffer
for something, you'll need to declare it before calling the function.Anyway, the equivalent C code would be: