I am getting segmentation fault error for argc argument. I am new to C language. Please help me to solve this.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int row1, row2, col1, col2, i, j, cnt=0;
int mat1[2000][2000], mat2[2000][2000];
printf("argc=%d", argc);
if (argc<5)
{
printf("\nPlease enter correct arguments <row_no_matrix1> <col_no_matrix1> <row_no_matrix2> <col_no_matrix2>\n");
exit(0);
}
row1 = atoi(argv[1]);
col1 = atoi(argv[2]);
row2 = atoi(argv[3]);
col2 = atoi(argv[4]);
printf("%d %d %d %d\n", row1, row2, col1, col2);
return 0;
}
Your matrices are too big for the stack on your machine. Each of the arrays has 4 million integers, or roughly 16 MiB of storage; that is a very big stack requirement.
Either reduce their size or allocate them dynamically.
Or (as noted in the comments), make them into variables with ‘static duration’, either within
mainwith the keywordstaticin front:or as file scope variables defined outside
main(), also with the keywordstaticin front:or as global variables defined outside
main()without the keywordstatic(but only do this if you will have multiple source files that need to access them by name):You could also (again, as noted in the comments) increase the stack size. However, I respectfully suggest that is probably the least satisfactory solution.
Fair question. How often do you think you’ll really need a pair of 4 million cell arrays, compared with how often will you be dealing with, say, under 100×100 arrays? Also, are you on Windows (with MSVC and C89) or non-Windows (with C99 or later), or on Windows with GCC?
Also, have you learned about pointers yet?
On the whole, I think you should opt for smaller size arrays. That is by far the simplest solution. If you must have big arrays, go with statically allocated arrays.
If that won’t work, we’ll have to go through the pointers, but it isn’t pretty.