I am working on code which will keep track of each time a specific element in an array is accessed. The array itself will be allocated dynamically based off of the inputs by the user, and so no functions that I have seen are what I'm looking for. To be more specific, how do I dynamically allocate the rows and columns of an array, and then initialize every element to 0?
Ex.
./SIM A B
int* array_columns = malloc(atoi(argv[1]) * sizeof(int));
int* array_rows = malloc(atoi(argv[2]) * sizeof(int));
int array[*array_rows][*array_columns];
everything that I have seen requires knowing beforehand the number of elements in each row/column. Can anyone give any pointers on how to initialize this array to 0? edit: I have added the line where I attempt to establish the array
This program allocates memory using command line parameters and creates a variable that can be accessed using array syntax. It uses calloc
to initialize values to zero:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int **array;
int length = atoi(argv[1]);
int width = atoi(argv[2]);
array = calloc(length, sizeof(int *));
for (int i = 0; i < length; i++) {
array[i] = calloc(width, sizeof(int));
}
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++) {
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
}
for (int i = 0; i < length; i++) {
free(array[i]);
}
free(array);
return 0;
}
Compiled With
gcc -Wall -Werror -o scratch scratch.c
Output
[user@machine]: ./scratch 3 5
array[0][0] = 0
array[0][1] = 0
array[0][2] = 0
array[0][3] = 0
array[0][4] = 0
array[1][0] = 0
array[1][1] = 0
array[1][2] = 0
array[1][3] = 0
array[1][4] = 0
array[2][0] = 0
array[2][1] = 0
array[2][2] = 0
array[2][3] = 0
array[2][4] = 0
Note
I left out input validation and error checking to keep the example small.
Compiler Options
I use -Wall -Werror
to turn on all warnings and treat them as errors. This means the compiler won't produce an executable unless all the causes of warnings are fixed. The -o scratch
tells the compiler what to name the output file.