I am a MacOS user and I want to write a function in C that assigns every element of a 2 dimensional (dynamically allocated) array a value of 0. But when I compile and run the program an error message
Exception has occurred. EXC_BAD_ACCESS (code=1, address=0x0)
pointing to the statement arr[i][j] = 0; appears.
#include <stdlib.h>
#include <stdio.h>
#define SIZE 8
/* assigns 0 to all elements of 2d array */
void clearArr(int **arr, int rows, int columns)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
arr[i][j] = 0;
}
}
}
int main(void)
{
int **arr = (int**)malloc(sizeof(int) * (size_t)SIZE);
for (int i = 0; i < SIZE; i++)
{
arr[i] = (int*)malloc(sizeof(int) * (size_t)SIZE);
}
clearArr(arr, SIZE, SIZE);
for (int i = 0; i < SIZE; i++)
{
free(arr[i]);
}
free(arr);
return 0;
}
Substituting it for "((arr + i) + j) = 0;" doesn't solve the problem.
You do not have 2D array only array of pointers. I would suggest using array pointers instead.
https://godbolt.org/z/o7ddfqnfc
Your code is invalid as you do not allocate the correct ammount of memory. You should: