I tried a lot of things to do but it still show me the same, that there is unhandled exception: access violation writing location in VS. But it doesn't happen when i sorting 1d array. What can I try next?
int main(void) {
static int a[3][4]{}, ab[3][4]{};
int i, j, k, N, M;
int* a1=nullptr;
printf("Matrica mora da ima velicinu 3 sa 4\n");
printf("Enter the order \n\n\t");
scanf_s("%d%d",&N ,&M);
for (i = 0;i < M;++i)
{
for (j = 0;j < N;++j)
{
scanf_s(" %d", &a[i][j]);
ab[i][j] = a[i][j];
}
printf("\n");
}
for (i = 0;i < M;++i) {
for (j = 0;j < N;++j) {
printf(" %d", a[i][j]);
}
printf("\n ");
}
//classic sorting
for (i=0; i < M; ++i)
{
for (j = 0;j < N;++j)
{
for (k = j + 1;j < N;++k)
if (a[i][j] > a[i][k])
{
*a1 = a[i][j]; // there is exception thrown
a[i][j] = a[i][k];
a[i][k] = *a1;
}
}
}
First off, there is a problem with static allocation of arrays, but there is no sanitization of
NandMafter the user inputs them. That means that you allocate only a matrix of3x4, but the user can input and write to a matrix of any dimensions (e.g.10x10), which could lead to access violation.I'd recommend either having sanitation of the input values, e.g.
In case the input didn't exceed
3x4, another thing that could be problematic -igoes from0toM, notN(what I would expect), which could also be problematic. The way matrix addressing works in C/Cpp is that the matrix is linearized into an array, and accessing it witha[i][j]leads to accessing the array witha[i*MAX_J + j]. In your case, the array has12elements (3x4), andMAX_J=4, so accessing it with a reverse set of indexesa[4][3]will accessa[4*4+3]=a[19], which will access memory from outside of the array.On the access violation writing problem,
a1isn't allocated, so when you try do execute*a1= ...you are writing tonullptr, which is a protected address, hence the access violation when writing. The way to solve this is either to:a1be aintvariable (not a pointer)a1by executinga1 = malloc(sizeof(int));and then freeing it after use withfree(a1)(but since it's only a single element, I'd recommend convertinga1tointinstead)a1=&a[i][j], but that would not be valid logically in your case (after that, you write into the location the pointer is pointing to, so the original value will be lost).The reason why it's not happening for the 1d array is probably because of the inverted dimensions - the matrix would probably be
1x4, but you will be accessing it as4x1, and you are sorting all the values withjindex from0to1, and since there is only one value you would not enter thekloop.