Reputation: 1
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.
Upvotes: 0
Views: 450
Reputation: 5011
Change this part :
int **custom2d;
custom2d = malloc(sizeof(int) * rows);
for (int i = 0; i < rows; i++)
{
*(custom2d + i) = malloc(sizeof(int) * cols);
}
to :
int **custom2d;
custom2d = malloc(sizeof(int*) * rows);
if (custom2d == NULL)
{
printf ("Error");
return;
}
for (int i = 0; i < rows; i++)
{
*(custom2d + i) = malloc(sizeof(int) * cols);
if (custom2d[i] == NULL)
{
printf ("Error");
return;
}
}
See this link on why you should check the result of malloc
. Also change :
scanf_s("%d", custom2d[i][j]);
to :
scanf_s("%d", &custom2d[i][j]);
Finally change :
int rows = scanf_s("%d", &rows);
and
int cols = scanf_s("%d", &cols);
to :
int rows;
scanf_s("%d", &rows);
and
int cols;
scanf_s("%d", &cols);
respectively, as right now you are using the return value of scanf_s
and not the values read.
Upvotes: 3
Reputation: 2790
You need to allocate an array of pointers (int *
) instead of int
custom2d = malloc(sizeof(int *) * rows);
and then for more readability, imho, you can also do:
custom2d[i] = malloc(sizeof(int) * cols);
in both cases you should check if the allocation has been done:
if (custom2d == NULL)
printf ("No allocation made");
and
if (custom2d[i] == NULL)
printf ("No allocation made");
Moreover you need to pass the pointer to scanf_s
:
scanf_s("%d", &custom2d[i][j]);
You need to change also this because scanf_s returns the number of fields successfully converted and assigned
int rows;
scanf_s("%d", &rows);
int cols;
scanf_s("%d", &cols);
Upvotes: 1