I malloc'ed an array of structs. In a loop over pointers to the separate structs then is checked if more structs are needed. If so, a realloc is used to increase the number of structs. However as the realloc might use a different chunk of memory, the old pointer to the last filled structure has to be updated to the new position in memory. What is the best way to keep track at which structure of the array the pointer was pointing last? The code below does not work, it halts with realloc(): invalid old size. I left away the checks for NULL after alloc for clarity.

```
#include <stdio.h>
#include <stdlib.h>

#define N 2
struct s 
{
  int a;
};
struct s **p;

int main() 
{
    struct s *q;
    int n = N;
    int i, j, m;

    p = malloc(n * sizeof(struct s *));
    for (i = 0 ; i < n ; i++)
        p[i] = malloc(sizeof(struct s));
    q = p[0];
    for (i = 0 ; i < 100 ; i++) 
    {
        if ((m = q - p[0] + 1) > n) 
        {
            printf("realloc at n %d\n", n);
            n *= 2;
            p = realloc(p, n * sizeof(struct s *));
            for (j = 0 ; j < n ; j++)
                p[j] = realloc(p[j], sizeof(struct s));
            q = p[m - 1];
        }
        q->a = i;
        q++;
    }
}

```