printf("\nNow its time to make a custom array. Please enter the number of rows: ");
int rows = scanf_s("%d", &rows);
printf("Now enter the number of columns: ");
int cols = scanf_s("%d", &cols);
int **custom2d;
custom2d = malloc(sizeof(int) * rows);
for (int i = 0; i < rows; i++)
{
*(custom2d + i) = malloc(sizeof(int) * cols);
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("Enter value for [%d][%d]: ", i, j);
scanf_s("%d", custom2d[i][j]);
}
}
I am very new to C but I know several other higher level languages. I can't understand why this code isn't working. When I get to the prompt for entering the array value at the index, I get an exception(access violation writing location). I am very confused. All I'm trying to do is allow the user to specify rows, columns, and then input a value at each location of the array.
int **is not a 2D array, nor can it point to one. It is a completely different construct.ptr_var = malloc(num * sizeof *ptr_var), in your case that would becustom2d = malloc(rows *sizeof *custom2d);andcustom2d[i] = malloc(cols * sizeof *custom2d[i]);.int rows = scanf_s("%d", &rows);→int rows; scanf_s("%d", &rows);,int cols = scanf_s("%d", &cols);→int cols; scanf_s("%d", &cols);.scanfreturns the number of items successfully matched and assigned, not the input value.