16

Sorry if this post comes off as ignorant, but I'm still very new to C, so I don't have a great understanding of it. Right now I'm trying to figure out pointers.

I made this bit of code to test if I can change the value of b in the change function, and have that carry over back into the main function(without returning) by passing in the pointer.

However, I get an error that says.

Initialization makes pointer from integer without a cast
    int *b = 6

From what I understand,

#include <stdio.h>

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

int main(){
       int * b = 6;
       change(b);
       printf("%d", b);
       return 0;
}

Ill I'm really worried about is fixing this error, but if my understanding of pointers is completely wrong, I wouldn't be opposed to criticism.

2

4 Answers 4

17

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 won't work because the logic will still be wrong )

int *b = (int *)6; //This is typecasting int into type (int *)
Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

Comments

2
#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;
}

Comments

0

Maybe too late, but as a complement to the rest of the answers, just my 2 cents:

void change(int *b, int c)
{
     *b = c;
}

int main()
{
    int a = 25;
    change(&a, 20); --> with an added parameter
    printf("%d", a);
    return 0;
}

In pointer declarations, you should only assign the address of other variables e.g "&a"..

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.