Convert C realloc to Delphi -
int stackrealloc(stack* s){ if ((s->array = realloc(s->array,sizeof(int)*(s->size)*2)) != null){ s->size = (s->size)*2; return 1; } else return 0; } how can convert code( c ) delphi ( delphi7 ) ?
the delphi function analagous c realloc reallocmem.
you could, if wished, make literal translation of c struct delphi record, , call reallocmem. in delphi use dynamic array instead of raw pointers:
var arr: array of integer; ... setlength(arr, length(arr)*2); there's no need struct contains both array , size because delphi dynamic array keeps track of own length.
what's more not signal errors using 0 or 1 return value. instead not write explicit error checking in code , let runtime raise exception should call setlength fail.
since appear implementing stack, use tstack class found in contnrs unit. in modern delphi use generics.collections.tstack<integer> instead.
as aside, c code broken. fails handle errors correctly. if call realloc fails, null returned. since store away s->array, lost track of original block of memory , therefore leak it. 1 of golden rules of c programming never write: p = realloc(p, ...).
Comments
Post a Comment