I have to write a program with dynamic 2d array but I've got a problem. Everything works fine until I try to print the array with more than 4 rows. Up to 4 rows all looks good, but with 5th row the length of last row expands to 7631472 which cause a segmentation fault.
Edit:
Thank you guys for response, I did what you'd suggested me,. However I discovered that problem is somewhere else, it's in "lengths" array. Each time when I add mroe than these 4 items it starts to fill up with some random values from memory.
Code:
#include <stdio.h>
#include <stdlib.h>
int addRow(int i, int **array2d, int * lengths) {
    int len, value;
    int counter;
    i++;
    scanf("%d", &len); /*write the length of each row*/
        *(array2d + i-1) = malloc(sizeof (int) * len);
        *(lengths + i-1) = len;
    for(counter = 0; counter < len; counter++) {
        scanf("%d", &value); /*write each element in row*/
        *(*(array2d+i-1)+counter) = value; 
    }
    return i;
}
void print(int *i, int **array2d, int * lengths) {
    int counter, counter2;
    for(counter = 0; counter < *i; counter++) {
        for(counter2 = 0; counter2 < *(lengths+counter); counter2++) {
            printf("%d ",*(*(array2d+counter)+counter2));
        }
        printf("\n");
    } 
}
void end(int *i, int **array2d, int * lengths, char * word) {
    int counter;
    for(counter = 0; counter < *i; counter++)
        free(*(array2d + counter));
    free(array2d);
    free(lengths);
    free(word);
}
int main() {
    int ** array2d = (int**) malloc (0*sizeof(int*));
    int * lengths = (int*) malloc (0*sizeof(int)); /*length of each row*/
    char * word = (char*) malloc (3*sizeof(char));
    int i, isEqual; /* i - number of rows */
    i = 0;
    while(1) {
        scanf("%s", word);
        isEqual = strcmp(word, "add");
        if(!isEqual)
        i = addRow(i, array2d, lengths);
        isEqual = strcmp(word, "print");
        if(!isEqual) 
            print(&i, array2d, lengths);
        isEqual = strcmp(word, "end");
        if(!isEqual) {
            end(&i, array2d, lengths, word);
            return 0;
        } 
    }
    return 0;
}
 
     
     
    