I have been trying to execute the following code. Though the task is trivial, I am getting a segmentation fault.
The aim of the code snippet betlow is to create a multi dimensional array of maximum row size 4 and column size 33. Then after creation, it should set the contents of all the rows as 0, followed by a '\0'
character. Then in the end, it should display the output on the stdout
.
Although I am not new to programming, I keep on getting similar errors, so if possible please explain me how can I avoid such mistakes in the future.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
int i,j,k,x,y;
char** arr;
arr = (char**) malloc(4 * sizeof(char*));
for ( i = 0; i < 4; i++) {
arr[i] = (char*) malloc(9 * sizeof(char));
memset(arr,0,8);
arr[i][8] = '\0';
}
for ( j = 0; j<4; j++) {
puts(arr[j]);
}
return 0;
}