-
realloc realloc realloc
Perhaps this will make the code I posted a little while ago easier to understand:
PHP Code:
/* if srchitem is found in the array, its position is
returned, however many times it occurs (the positions
are to be written to 'foundpositions' array).
size is the size of the array, fsize is the size of
the positions array. */
int *seqsearch (double *ara, double srchitem, int size) {
int *foundpositions;
int fsize = 0; // size of foundpositions
for ( int x=0; x<size; x++)
if (*(ara+x) == srchitem) {
foundpositions = (int *) realloc (foundpositions, ( (fsize+1)*sizeof(int) ));
// allocate memory to foundpositions array
// as elements matching srchitem are found.
fsize ++;
*(foundpositions+x) = x;
}
return (foundpositions);
}
:)
-
Try initialising your foundpositions to NULL.
-
Doesn't realloc initialize it to null the first time anyway?
-
No, that actually worked, thanks!
-
>Doesn't realloc initialize it to null the first time anyway?
realloc doesn't have to move the allocated block. If it initialised the pointer to NULL everytime then it may be destroying your previously allocated data. How does it know that it's the first time?