Is there an elegant way to pass a pointer to a function that might not even be needed?
For example, one way I've been able to do something is:
Code:
void function()
{
int* thing = malloc(<some size>);
int size = 0;
while(# of iterations)
{
someFunction(thing, &size);
someOtherFunction(thing);
}
}
void someFunction(int* thing, int*size)
{
if(somethingHappens)
{
if(*size > 0)
thing = (int*)realloc(sizeof(int) * (*size + 1));
thing[size] = someData;
size++;
}
//other stuff goes here
}
But doing it the way above, if someFunction isn't used that much the program could run fine, but if its used a lot, a lot of wierd memory problems occur.
Also I tried:
Code:
void function()
{
int* thing = 0;
int size = 0;
while(# of iterations)
{
someFunction(thing, &size);
someOtherFunction(thing);
}
}
void someFunction(int* thing, int*size)
{
if(somethingHappens)
{
if(*size == 0)
thing = (int*)malloc(sizeof(int));
else
thing = (int*)realloc(thing, sizeof(int) * (*size + 1));
thing[size] = someData;
size++;
}
//other stuff goes here
}
But if 'thing' is malloc'd inside someFunction() when the function returns 'thing' is NULL in Function().
So the only way I actually got it to work without memory problems is to make 'thing'
global, but it seems like a very unelegant solution. Is there a better way to do this?