Say I want to dynamically allocate memory but with a function instead of in the main() function.
So I tried to do this:
dynamAlloc(int *fPtr)
{
fPtr=malloc(cols * sizeof(*fPtr) );
if(fPtr==NULL)
{
printf("Can't allocate memory");
exit(1);
}
}
Then I realised: Even though memory allocated on the heap is available for the lifetime of program, that memory can only be referenced by formal argument fPtr and not the actual argument(let's call it aPtr). But once, function is exited, that memory is lost.
So how then do I dynamically allocate memory with a function?
formal arument fPtr and not the actual argumen- what is a "formal argument"? what is an "actual argument"? How do they differ? Are you asking how to assign a value to a variable from outer scope from a function?assign a memory block- a pointer is not a memory block, it's just an address to the memory.int *fPtrwithint **fPtrto receive&aPtras argument?dynamAlloc(int **fPtr)and then*fPtr=malloc(cols * sizeof(**fPtr) );Otherwise you are assigning the allocated block to a copy of the pointer that is local to the function so the allocation is never seen back inmain()(and is essentially a memory-leak). Call withdynamAlloc (&pointer)inmain().*operaters made it look harder than it actually is but I realised the concept is still the same. Much thanks for showing me the way!