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