0

Something like this:

struct s
{
    int a;
    int b;
}

void f(struct s **a)
{
    a[0][0].a = 0; // Access violation here
}

int main()
{
    struct s a[5][3];
    f(a);
    return(0);
}

So how can I access content of a inside function f using 2D array notation?

fdermishin
  • 3,519
  • 3
  • 24
  • 45
Jamesits
  • 612
  • 7
  • 18

1 Answers1

2

An array like a[5][3] stores the struct instances contigously, while struct s **a will store pointers contigously such that each pointer points to one instance of struct s. So struct s a[5][3] (which is automaticaly converted to a pointer) and struct s **a are incompatible pointers, if you compile with warnings you would know that.

A simple solution would be

void f(struct s a[][3])
{
    a[0][0].a = 0; // Access violation here
}

A better solution, is

#include <stdlib.h>

struct some_structure
{
    int value1;
    int value2;
};

void
set_value(struct some_structure **array, size_t row, size_t column)
{
    array[row][column].value1 = 0;
    array[row][column].value2 = 0;
}

int
main(void)
{
    struct some_structure **array;
    array = malloc(5 * sizeof(*array));
    if (array == NULL)
        return -1; // Allocation Failure
    for (size_t i = 0 ; i < 5 ; ++i)
    {
        array[i] = malloc(sizeof(*(array[i])));
        if (array[i] == NULL)
            return -1; // Allocation Failure
    }
    set_value(array, 0, 0);
    for (size_t i = 0 ; i < 5 ; ++i)
        free(array[i]);
    free(array);
    return 0;
}

As you see when I say above will store pointers it is because you need to allocate memory for that, you can by using malloc() like the example above.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97