A segmentation fault error with 2D array

前端 未结 2 1223
情书的邮戳
情书的邮戳 2021-01-22 16:07

There is a weird segmentation fault error. The following code runs fine

#include  
#include 
main()
    {
    int matrixSize = 100         


        
2条回答
  •  滥情空心
    2021-01-22 16:53

    As tpg2114 says allocating as large matrices is not a good idea. Easiest is to allocate it like that

    double (*a)[matrixSize] = malloc(sizeof(double[matrixSize][matrixSize]));
    .
    free(a);
    

    Then you can continue to use your nested for loops for initialization without problems as before.

    NB:

    • since you use a variable for the dimensions your matrix is technically a variable length array, that is only available with C99
    • your definition for main is not conforming to the standard. In your case you should use int main(void) { ... }. since a conforming compiler should capture this, it looks that you don't use the correct options for your compiler or that you ignore warnings that he gives you.
    • since they are representing sizes, your variables matrixSize, i and j should be of type size_t and not int.

提交回复
热议问题