-2

I'm sort of confused between these 2 declarations

  1. int *a;
  2. int (*a)[3]

As I understand it, both of these give us a single pointer pointing to nothing in memory. The 2nd one is shown to be an example of a pointer pointing to an array of 3 ints in memory. But since this memory has not even been allocated, does it make any sense.

To make the pointer point to an array of 3 ints in memory, we need to do a a = (int*)malloc(sizeof(int) * 3). Doing this for the first one AND the second one will both give me a pointer pointing to a memory location where 12 consecutive bytes store my 3 numbers.

So why use int (*a)[3] at all if eventually I have to use malloc ?

tsaebeht
  • 1,570
  • 5
  • 18
  • 32
  • 1
    Do you understand the difference between `int *a;` and `float *f;` ? If you can answer that, then the same answers apply to your question. – M.M Jun 09 '19 at 07:48

2 Answers2

4

So why use int (*a)[3] at all if eventually I have to use malloc ?

It is very useful for variable length arrays when you want to create a real 2d array using dynamic memory:

#include <stdio.h>
#include <stdlib.h>

void *fn_alloc(int rows, int cols)
{
    int (*arr)[cols];
    int i, j;

    arr = malloc(sizeof(int [rows][cols]));
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            arr[i][j] = (i * cols) + j;
        }
    }
    return arr;
}

void fn_print(int rows, int cols, int (*arr)[cols])
{
    int i, j;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("\t%d", arr[i][j]);
        }
        printf("\n");
    }
}

int main(void)
{
    int rows, cols;

    scanf("%d %d", &rows, &cols);

    int (*arr)[cols] = fn_alloc(rows, cols);
    fn_print(rows, cols, arr);
    free(arr);
    return 0;
}

In other words, when dynamic memory is involved, your first declaration is useful for pointing to an array of n dimensions while the second one is useful to point to an array of array of n dimensions.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

So why use int (*a)[3] at all if eventually I have to use malloc ?

Because in most such cases (dynamically sized 2D matrixes), you should have some abstract data type using flexible array members. This answer is very relevant to your question (which is a near duplicate).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547