【问题标题】:Incompatible Type Error when trying to store an array of pointers尝试存储指针数组时出现不兼容的类型错误
【发布时间】:2011-04-29 10:55:38
【问题描述】:

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

错误:从类型“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
    }
}

【问题讨论】:

    标签: c


    【解决方案1】:

    counters[i]struct counter 类型; makeNewCounter() 返回一个 struct counter * 类型的值,编译器理所当然地抱怨。

    试试

    counters[i] = *makeNewCounter();
    

    struct counter **counters;
    

    【讨论】:

      【解决方案2】:

      这是因为 counters 的类型是 counter *。使用方括号运算符 [] 您正在取消引用指针,这样您现在正在处理一个真实的结构。不是指向它的指针!

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

      【讨论】:

        【解决方案3】:
        static struct counter* counters
        

        需要:

        static struct counter** counters
        

        【讨论】:

          【解决方案4】:

          更正:静态结构 counter** counters = NULL;

          现在 counters 是一个指向结构计数器的指针。这样就可以保存了。

          希望对你有帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-02-21
            • 2020-05-22
            • 1970-01-01
            • 1970-01-01
            • 2019-11-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多