尝试存储指针数组时,不兼容的类型错误

时间:2011-04-29 10:55:38

标签: c

嘿,我正在尝试存储一个指针数组(到结构)但是我一直在收到错误

  

错误:从类型'struct counter *'

中分配类型'struct counter'时出现不兼容的类型

但据我所知,代码是正确的。有什么想法吗?

struct counter 
{
   long long counter;            /* to store counter */
};

static struct counter* counters = NULL;

struct counter* makeNewCounter(void)
{
    struct counter* newCounter = malloc(sizeof(struct counter));
    newCounter->counter = 0;
    return newCounter;
}

static void setUpCounters(void)
{   
    counters = malloc(ncounters * sizeof(struct counter*));

    int i;
    for (i = 0; i < ncounters; i++)
    {
              counters[i] = makeNewCounter(); //This is the line giving the error
    }
}

4 个答案:

答案 0 :(得分:2)

counters[i]的类型为struct counter; makeNewCounter()返回类型struct counter *的值,编译器正确地抱怨。

尝试

counters[i] = *makeNewCounter();

struct counter **counters;

答案 1 :(得分:1)

这是因为计数器的类型为counter *。使用括号运算符[],您将取消引用指针,以便您现在处理实际结构。不是它的指针!

但是你的函数makeNewCounter()返回一个指针,所以这就是它不适合的点。左侧有一个类型计数器,右侧有类型计数器*

答案 2 :(得分:0)

static struct counter* counters

需要:

static struct counter** counters

答案 3 :(得分:0)

更正:静态结构计数器** 计数器= NULL;

现在,counter是指向struct counter的指针。这样你就可以存储它。

希望有所帮助