0

I am very new to C, and I am trying to get a int **data to represent a matrix of integers. I first created an array of arrays, then I tried referencing the pointer of pointer to that array like so:

int **pointer;
int data[num_rows][num_cols];
pointer = (int**) data[0];

However I get a warning: cast to pointer from integer of a different size. Can someone please help me understand what is going on, and how can I assign an array to int **pointer? (I have to use the double pointer)

  • You cannot assign an array to an `int **`. An array is a number of objects in memory. **An array is not a pointer.** In most expressions, an array is automatically converted to a pointer to its first element. `data[0]` is an array, so it is converted to a pointer to its first element, resulting in `&data[0][0]`, which is the address of an `int`. So it is an `int *`. It is not an `int **`. To make an `int **`, you would first need to make an object that is an `int *`, and then you can take its address to get an `int **`. But this is not a good path. Why do you “have to use the double pointer”? – Eric Postpischil Feb 01 '20 at 15:39
  • @EricPostpischil "An array is a number of objects in memory. " - please explain – nicomp Feb 01 '20 at 15:49
  • @nicomp: C 2018 6.2.5 20 says “… An *array type* describes a contiguously allocated nonempty set of objects with a particular member object type…” – Eric Postpischil Feb 01 '20 at 15:51

1 Answers1

0

The line int data[num_rows][num_cols]; does not actually declare an "array of arrays!" Rather, it declares a single array with two dimensions - in memory, this will be a single block of data, of size num_rows x num_cols x sizeof(int).

To get an "array of arrays" that you can access using a 'double pointer', you generally have to use the malloc function. Something like the following:

int **pointer = malloc(num_rows * sizeof(int*)); // allocate an array of pointers
for (int i = 0; i < num_rows; ++i) {
    pointer[i] = malloc(num_cols * sizeof(int)); // allocate each row array
}

You can then access any [row][column] element via the double pointer:

pointer[row][column] = 1234;

When you've finished with the array(s), be sure to free the memory, like this:

for (int i = 0; i < num_cols; ++i) {
    free(pointer[i]); // free each row array
}
free(pointer); // free the array of arrays

Alternatively, given your int data[num_rows][num_cols]; you could avoid the malloc calls inside the for loop, as follows:

int **pointer = malloc(num_rows * sizeof(int*)); // allocate an array of pointers
for (int i = 0; i < num_rows; ++i) {
    pointer[i] = &data[i][0]; // Assign a pointer to the beginning of each row
}

Feel free to ask for further clarification and/or explanation.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83