[英]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. 我有以下问题:我需要初始化一个代表数字的stuct数字,为此它需要包含它的值,除数和自身的除数。 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. 在main函数中,我为每个字段分配一个值。 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]
[警告]从不兼容的指针类型分配[默认启用]
int (*divisors)[];
is wrong this is a pointer to array of int
. 这是错误的,这是指向
int
数组的指针。
use 采用
int *divisors;
with this your malloc
allocation should work. 有了这个你的
malloc
分配应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.