嘿,我正在尝试用C ++重写代码以在C中工作。我基本上只是想在C中找到新的和删除的等价物,但它不是很有用,这是我的代码:
这是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 *”类型的实体
答案 0 :(得分:3)
你只需要施展它 -
eventBuffer = (INPUT_RECORD*) malloc(numOfEvents * sizeof(*eventBuffer));
当然,有人会说,标准说你不必投出“malloc”的结果。显然,在这种情况下,标准是无关紧要的:)
答案 1 :(得分:1)
您的C ++代码不起作用。您将eventBuffer
传递给ReadConsoleInput()
,但仅在您声明它之后:
// 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];
如果ReadConsoleInput()
需要eventBuffer
,则需要在调用函数之前声明它。
无论如何,等效的C代码将是:
INPUT_RECORD* eventBuffer;
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
eventBuffer = (INPUT_RECORD*) malloc(numOfEvents * sizeof(INPUT_RECORD));