Initialization makes pointer from integer without a cast – C

Initialization makes pointer from integer without a cast – C

To make it work rewrite the code as follows –

#include <stdio.h>

int change(int * b){
    * b = 4;
    return 0;
}

int main(){
    int b = 6; //variable type of b is int not int *
    change(&b);//Instead of b the address of b is passed
    printf(%d, b);
    return 0;
}

The code above will work.

In C, when you wish to change the value of a variable in a function, you pass the Variable into the function by Reference. You can read more about this here – Pass by Reference

Now the error means that you are trying to store an integer into a variable that is a pointer, without typecasting. You can make this error go away by changing that line as follows (But the program wont work because the logic will still be wrong )

int * b = (int *)6; //This is typecasting int into type (int *)

Maybe you wanted to do this:

#include <stdio.h>

int change( int *b )
{
  *b = 4;
  return 0;
}

int main( void )
{
  int *b;
  int myint = 6;

  b = &myint;
  change( &b );
  printf( %d, b );
  return 0;
}

Initialization makes pointer from integer without a cast – C

#include <stdio.h>

int change(int * b){
     * b = 4;
     return 0;
}

int main(){
       int  b = 6; // <- just int not a pointer to int
       change(&b); // address of the int
       printf(%d, b);
       return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *