Wednesday, December 11, 2019

Allocating of heap memory inside function with doubly nested pointers

just a cut/paste of template/pattern code here so i don't have to spend 10 minutes dancing with the compiler.

#include
#include
#include

#define SIZE 10

void fooAllocator(unsigned int** image)
{
*image = (unsigned int *) malloc(SIZE * sizeof(unsigned int));

if (*image != NULL) //resolves MSVC compiler error, just a little test before the real loop
{
(*image)[7] = 14;
}
for (int i = 0; i < SIZE; i++)
{
(*image)[i] = 66;
}
}

void fooWriter(unsigned int* image)
{
for (int i = 0; i < SIZE; i++)
{
image[i] = 42;
}
}

void printImage(unsigned int* image)
{
for (int i = 0; i < SIZE; i++)
{
printf("[%d]=%d\n", i, image[i]);
}
}

int main()
{
unsigned int* image = NULL;

//function that allocates memory for image
fooAllocator(&image);
printImage(image);
fooWriter(image);
printImage(image);

for (int i = 0; i < SIZE; i++)
{
image[i] = 36;
}

printImage(image);
return 1;
}

No comments: