Search code examples
arrayscpointersintegeransi-c

Initializing a pointer to an array of integers.


I have the following problem: I need to initialize a stuct Number that represents a number, for this it needs to contains its value, amount of divisors and the divisors themself. To store the divisors I need to use a pointer to an array of integers, and this is where the problem starts.

 typedef struct {
        int value;
        int divisor_amount;
        int (*divisors)[];
    } Number;

Now since I do not know in advance how many divisors my number posseses I cannot give a length to the array.

In the main function I assign each of these fields a value. For the first two variables this is no problem.

Number six;
six.value = 6;
six.divisor_amount = 3;

Now for the pointer I do not really know how to initialize it. During class it was told to do this as:

six.divisors[0] = 1;
six.divisors[1] = 2;
six.divisors[2] = 3;

but then I get this erroy from the compiler:

[Error] invalid use of array with unspecified bounds

So I thought maybe I needed to assign some space and tried:

six.divisors = malloc(six.divisor_amount*sizeof(int));

But that gives me just another error:

[Warning] assignment from incompatible pointer type [enabled by default]


Solution

  • int (*divisors)[];
    

    is wrong this is a pointer to array of int.

    use

    int *divisors;
    

    with this your malloc allocation should work.