简体   繁体   中英

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"

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 * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM