开发者

Incompatible Type Error when trying to store an array of pointers

Hey, I'm trying to store an array of pointers (to structs) but am continually receiving the error

error: incompatible types when assigning to type 'struct counter' from type 'struct counter *'

But as far as I know, the code is correct. Any ideas?

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

static struct counter* counters = NULL;

struct counter* makeNewCounter(void)
开发者_如何学Python{
    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
    }
}


counters[i] is of type struct counter; makeNewCounter() returns a value of type struct counter * and the compiler rightfully complains.

Try

counters[i] = *makeNewCounter();

or

struct counter **counters;


This is because counters is of type counter *. Using the bracket operator [] you are dereferencing the pointer such that you are now dealing with a real structure. Not a pointer to it!

But your function makeNewCounter() returns a pointer, so this is the point where it doesn't fit. The left side has a type counter, the right side has type counter *


static struct counter* counters

needs to be:

static struct counter** counters


Correction : static struct counter** counters = NULL;

Now counters is a pointer to pointer to struct counter. That way you can store it.

Hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜