I have a struct which is called "visitor" and I want to write function which allocates the memory for my pointer to this struct ...
this Codes works:
visitor *visitorPtr = NULL;
int visitorCounter = 0;
visitorPtr = realloc(visitorPtr, ((visitorCounter++) * sizeof(visitor)));
but now I wanted to put this functionality to a function
void getMoreSpace(void *ptr, unsigned int counter)
{
counter++;
ptr = realloc(ptr, counter * sizeof(visitor));
if (ptr == NULL)
{
printf("\n Error allocating memory! \n");
return EXIT_FAILURE;
}
}
//Call in MAIN:
getMoreSpace(visitorPtr, visitorCounter);
Unfortunately it seems not to work because I cant create data for this pointer and get this Error when I make that for that struct: Exception thrown at 0x0FDAE559 (ucrtbased.dll) in My-C-Project.exe: 0xC0000005: Access violation writing location 0x00000000.
visitorPtr
is passed as value to getMoreSpace
function. Thus any changes done to ptr
within the function will not update the vistorPtr
in main.
What you need is call the function by reference as below.
void getMoreSpace(void **ptr, unsigned int counter)
{
counter++;
*ptr = realloc(*ptr, counter * sizeof(visitor));
if (*ptr == NULL)
{
printf("\n Error allocating memory! \n");
}
}
And from main
you call as below.
getMoreSpace(&visitorPtr, visitorCounter);
if (visitorPtr)
...do stuff....
User contributions licensed under CC BY-SA 3.0