Your code should look like
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
int j = 0;
int lenRow = 0;
int rows = 0;
printf("Enter number of rows: ");
scanf("%d", &rows);
int** arr = malloc(rows * sizeof(int*));
if (NULL == arr)
{
printf("Unseccess\n");
return 1;
}
for (i = 0; i < rows; i++)
{
printf("Enter array length for row %d: ", i);
scanf("%d", &lenRow);
arr[i] = malloc(lenRow * sizeof(int));
if (arr[i] != NULL)
{
for (j = 0; j < lenRow; j++)
{
printf("Enter value for array: ");
scanf("%d", &arr[i][j]);
}
}
else
{
printf("Unseccess\n");
return 1;
}
}
for (i = 0; i < rows; i++)
free(arr[i]);
free(arr);
}
Many things:
- You are not allocating a 2D array: you are allocating a matrix where rows can have different length
- indices of matrix, using c start form 0 up to len-1, so
for (j = 1; j <= lenRow; j++)
---- must be ---> for (j = 0; j < lenRow; j++)
- Freeing a pointer to pointer dynamically allocated you must de-allocate all rows first.
4.Each element of a row is "pointed" using 2 coordinates [row][col] so
scanf("%d", &arr[j]);
must be scanf("%d", &arr[i][j]);
- Lastly you must always check the
malloc
return value before tio use it
EDIT
To print inserted data you must trace all width of each row, like:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
int j = 0;
int lenRow = 0;
int rows = 0;
printf("Enter number of rows: ");
scanf("%d", &rows);
int** arr = malloc(rows * sizeof(int*));
int *widths = malloc(rows * sizeof(int));
if ((NULL == arr) || (widths == NULL))
{
printf("Unseccess\n");
return 1;
}
for (i = 0; i < rows; i++)
{
printf("Enter array length for row %d: ", i);
scanf("%d", &lenRow);
widths[i] = lenRow;
arr[i] = malloc(lenRow * sizeof(int));
if (arr[i] != NULL)
{
for (j = 0; j < lenRow; j++)
{
printf("Enter value for array: ");
scanf("%d", &arr[i][j]);
}
}
else
{
printf("Unseccess\n");
return 1;
}
}
for (i=0; i<rows; i++)
{
for(j=0; j<widths[i]; j++)
{
printf("Matrix[%d][%d] = %d\n", i, j, arr[i][j]);
}
}
for (i = 0; i < rows; i++)
free(arr[i]);
free(arr);
free(widths);
}