How do I correctly set up, access, and free a multidimensional array in C?

后端 未结 5 981
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:31

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is

5条回答
  •  一个人的身影
    2020-11-22 00:02

    Going off of Jen's answer, if you want to allocate space for a 3D array, in the same manner, you can do

    int(*A)[n][n] = malloc(sizeof(int[num_of_2D_arrays][n][n]));
    
    for (size_t p = 0; p < num_of_2D_arrays; p++)
      for (size_t i = 0; i < n; i++)
        for (size_t j = 0; j < n; j++)
          A[p][i][j] = p;
    
    for (size_t p = 0; p < num_of_2D_arrays; p++)
        printf("Outter set %lu\n", p);
        for (size_t i = 0; i < n; i++)
          for (size_t j = 0; j < n; j++)
            printf(" %d", A[p][i][j]);
          printf("\n");
    
    free(A);
    

提交回复
热议问题