2

I wrote a program to read array elements at run time, where it then changes the column based on some configuration.

I get the following warning message from GCC cygwin compiler:

pointer.c:73: error: incompatible types in assignment

Considering the code below, how can I remove this warning?

Thank you in advance for your help

typedef struct INPUT_ST
{
    float a;
    float b;
    float c;
}INPUT;
const INPUT lookup[3][3];
main()
{
    INPUT *ptr;
    /*typedef INPUT (st[3][3]);*/
    INPUT (*ptr1)[3][3];
    int i, j;
    ptr = (INPUT *)&lookup;
    (*ptr1)[3][3] = &lookup[0][0];

    for(i=0; i<3; i++)
    {
        for(j=0; j<3; j++)
        {
            printf("Row %d and column %d:\n", i, j);
            printf("%f\n", (*ptr1)[i][j].a);
            printf("%f\n", (*ptr1)[i][j].b);
            printf("%f\n\n", (*ptr1)[i][j].c);
        }
        printf("\n");
    }
}
2
  • 3
    I would start by telling what's on line 73. Commented Apr 30, 2012 at 20:46
  • It's line 15 in the example code provided. Commented Apr 30, 2012 at 22:52

1 Answer 1

1

The line causing the error is the following:

(*ptr1)[3][3] = &lookup[0][0];

The reason is that the left-hand-side and right-hand-sides of the assignment have incompatible types.

ptr1 on the left is of type INPUT (*)[3][3] (a pointer to a 3x3 array of INPUT). (*ptr1)[3][3] is of type INPUT (dereferencing the (uninitialized) pointer and then accessing the (out-of-bounds) element [3][3]). lookup on the right is of type const INPUT [3][3] (3x3 array of const INPUT). That makes &lookup[0][0] to be of type const INPUT * (the address of the element [0][0]). So the types are conflicting: INPUT vs. const INPUT *.

What you are really trying to do is to make the ptr1 pointer point to the array lookup. So you need to add const to the pointer declaration and then initialize it as follows:

const INPUT (*ptr1)[3][3];
// ...
ptr1 = &lookup;

The partial solution you have with ptr doesn't work because it is a regular pointer (single dimension), so you cannot access ptr[i][j], that would mean to dereference INPUT which is not a pointer (but you could access ptr[i*3+j] instead of ptr[i][j]). By the way, instead of casting away the const as you do for ptr you should really declare ptr as const INPUT *ptr;.

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.