2

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]

3
  • 3
    int (*divisors)[]; is probably not what you want to have. If you want to have a pointer to an array just write int *divisors; and then malloc it during initialisation Commented Oct 18, 2014 at 12:56
  • I cannot reproduce the warning. As six.divisors is a (non-function) pointer type, this should actually work. The error message for the first snippet is the same as gcc -std=c99 gives, but I don't get the second one. How do you compile? Commented Oct 18, 2014 at 17:10
  • I use devcpp with -Wpedantic turned on. Commented Oct 20, 2014 at 17:29

1 Answer 1

3
int (*divisors)[];

is wrong this is a pointer to array of int.

use

int *divisors;

with this your malloc allocation should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.