I'm attempting to create a dynamic unsigned char array that grows in number of rows per each element added:
#include <stdio.h>
#include <stdlib.h>
#define BLOCKSIZE 1
int main()
{
unsigned char **p = NULL, rows = 0;
// initialize p pointer to as the size of one char
p = malloc ( BLOCKSIZE * sizeof ( unsigned char *) );
// add 10 "TEST" elements
for (;rows < 10; rows++ )
{
if (rows > BLOCKSIZE) {
// allocate memory for each row
p = realloc (p, rows * sizeof ( unsigned char *) );
}
// allocate memory for each column
p[rows] = malloc (rows * sizeof (unsigned char ));
// add element
p[rows] = "TEST";
}
for (int i=0; i < rows; i++)
printf("%s\n", p[i]);
return 0;
}
The code outputs this error when run:
realloc(): invalid next size
Aborted (core dumped)
Could someone please explain to me what I am doing wrong?