0
void main(){
float a = 5;
float *test;
*test = a;
}

This doesn't compile. Why? I mean there is instantly a bug that pointer variable cannot be used without initializaiton.

Here's a link to the error https://i.sstatic.net/nWCVY.png

5
  • Please show the actual compiler error. Commented Nov 27, 2014 at 12:54
  • added a link in the main post Commented Nov 27, 2014 at 12:54
  • Are you sure you don't want test = &a; ? Commented Nov 27, 2014 at 12:55
  • @Greyshack You obviously compiled the code.... Commented Nov 27, 2014 at 12:55
  • Yeah I know it's compiled, I used the wrong word sorry ;d I don't know how to call it Commented Nov 27, 2014 at 12:56

3 Answers 3

1
void main(){
float a = 5;
float *test;  // now the pointer test contains a random value
              // and because it can be anything it is not safe to access that memory
*test = a;    // not safe!. Dereferencing a random address will give garbage.
}

Use test = &a if you want the pointer to have the address of the variable a.

Sign up to request clarification or add additional context in comments.

Comments

1
test = &a;

The thing is when you declare the pointer variable, it doesn't get an address, but it's a variable address. So if you have to change directly the address, using what I've write at the first line.

Using *test will change the content (so if *test = 1 and a = 2, when you do *test = a, the content of test will be 2). Because there's no content at the declaration of *test, you can't modify something that just doesn't exist.

after, a little trick to be more efficient (and so haven't to create pointer like you do) :

void function(int *a); /* declaration */
function(&a); /* call */

when you modify "a" in the function, it'll be modify in the main because of the address : you change the content, not the container.

*a = 1;

in the main you'll now have a == 1

Comments

0

This does not work because at that point the pointer doesn't point to anything (dangling pointer), still you tell it to assign the value found in a wherever he's pointing. And this is the problem. It can't assign a value to nothing.

You have to give it the address of a variable to point at. After that you can deference it and assign values to that variable with the help of the pointer.

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.