开发者

Dynamically Sized Input Buffer for Console Game in C

开发者 https://www.devze.com 2023-03-02 08:17 出处:网络
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:

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 e开发者_JAVA技巧ntity of type "INPUT_RECORD *"


You just have to cast it --

eventBuffer = (INPUT_RECORD*) malloc(numOfEvents * sizeof(*eventBuffer));

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 :)


Your C++ code doesn't work. You pass eventBuffer to ReadConsoleInput() but it's only later that you declare it:

  // 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];

If ReadConsoleInput() needs eventBuffer for something, you'll need to declare it before calling the function.

Anyway, the equivalent C code would be:

INPUT_RECORD* eventBuffer;
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
eventBuffer = (INPUT_RECORD*) malloc(numOfEvents * sizeof(INPUT_RECORD));
0

精彩评论

暂无评论...
验证码 换一张
取 消