How to declare a variable size 2D array in C?

前端 未结 3 1281
太阳男子
太阳男子 2021-01-02 10:07

I have a problem with a project. I have to make a variable size 2D array for storing some prediction error..so this is about images. The trouble is that I have to load image

相关标签:
3条回答
  • 2021-01-02 10:29

    If you have a modern C compiler (at least C99) in function scope it is as simple as:

    unsigned arr[n][m];
    

    this is called a variable length array (VLA). It may have problems if the array is too large. So if you have large images you could do:

    unsigned (*arr)[m] = malloc(sizeof(unsigned[n][m]));
    

    and later

    free(arr);
    
    0 讨论(0)
  • 2021-01-02 10:29

    If you need the memory to be contiguous, you have a couple of choices.

    You could dynamically allocate a single block of memory, and then compute your offsets manually, like so:

    size_t rows, cols;
    ...
    int *arr = malloc(sizeof *arr * rows * cols);
    ...
    arr[i * rows + j] = ...; // logically equivalent to arr[i][j]
    

    You could set up a second array of pointers into the main array:

    int **arrp = malloc(sizeof *arrp * rows);
    ...
    for (i = 0; i < rows; i++)
      arrp[i] = &arr[i * rows];
    ...
    arrp[i][j] = ...;
    

    remembering that you would have to free both arr and arrp.

    If you have a C99 implementation, you can just set up a pointer to a VLA, like so:

    int (*arrp)[cols] = (int (*)[cols]) arr;
    ...
    arrp[i][j] = ...;
    

    Note that in this case, you're not allocating any memory for a secondary array, nor do you need to manually compute pointers into the main array; all you have to do is set arrp to the same location as arr and let the rules of pointer arithmetic do all the work.

    If the images aren't that big, you could just set up a VLA (again, C99 or later):

    int arr[rows][cols];
    

    but in practice this isn't a good idea; stack frames are usually pretty limited in size.

    0 讨论(0)
  • 2021-01-02 10:55

    You need to allocate memory dynamically. Use double pointer logic.

    Ex:

    int n=10; <<-u can change this.
    int **a;
    a=(int **)malloc(sizeof(*int)*n);
    for (int i=0;i<n;i++){
     a[i]=(int *)malloc(sizeof(int)*n);// or *(a+i)
    }
    
    0 讨论(0)
提交回复
热议问题