abubakarMana01
abubakarMana01

Reputation: 13

My compiler returned "assignment to 'int *' from incompatible pointer type 'char *' [-Wincompatible-pointer-types]" when I ran my C program

#include <stdio.h>
int main()
{
    char grade = 'A';
    int *p = &grade;
    printf("The address where the grade is stored: %p\n", p);
    printf("Grade: %c\n", grade);
    return 0;
}

I get this error each time I compile the code on VScode but never on code blocks.

warning: incompatible pointer types initializing 'int *' with an
      expression of type 'char *' [-Wincompatible-pointer-types]
    int *p = &grade;
         ^   ~~~~~~
1 warning generated.
 ./main
The address where the grade is stored: 0x7ffc3bb0ee2b
Grade: A"

Upvotes: 1

Views: 5366

Answers (1)

klutt
klutt

Reputation: 31389

The warning tells you exactly what it is. It says:

incompatible pointer types initializing 'int *' with an expression of type 'char *'

This means that p is of type int *, that &grade is of type char *, and that these two pointers are not compatible. The solution is to change the declaration of p to:

char *p = &grade;

One more thing. Usually you can safely do implicit conversions to and from any pointer to void *, but not when passed as argument to a variadic function. If you want to print the address, use this:

printf("%p", (void *)p);

But only cast when needed. Never do it just to get rid of warnings. Here is an answer I wrote about that: https://stackoverflow.com/a/62563330/6699433

As an alternative, you could use a void pointer directly:

void *p = &grade;
printf("%p", p);

But then you would need to cast if you want to dereference it. For example:

char c = *(char*)p;

That cast is not necessary if p is declared as char *.

Upvotes: 1

Related Questions