Hi everybody, hope you can help me with a problem i got
I wrote a c++ program using elements of dynamic memory, and writing the code below i i got the error "invalid conversion from `unsigned int' to `unsigned int*'". I'm more or less a beginner, so I don't even know what the "*" in "unsigned int*". Anybody who could help?
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main ()
{
unsignedint are, wid, hei, *ar2;
cin >> wid >> hei;
are = wid * hei;
ar2 = newunsignedint;
ar2 = are;
}
The "*" designates a pointer. You are allocating space for an unsigned int with new() but when you make the assignment you need to dereference ar2:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main ()
{
unsignedint are, wid, hei, *ar2;
cin >> wid >> hei;
are = wid * hei;
ar2 = newunsignedint;
*ar2 = are; // stores the value in are in the allocated space pointed to by ar2
delete ar2; // always delete() what you new()
}
the '*' symbol means 'pointer of' , then 'unsigned int *' is 'pointer of unsigned int' . when you write unsignedint ar, *ar2 you are declaring a variable named 'ar2' that is a pointer of unsigned int values and a variable named 'are' that contain an unsigned int. To modify the value pointed by a pointer, is used the deference operator '*' before the pointer, for example:
1 2 3 4 5 6 7
unsignedint a , *b; //declaring an 'unsigned int' variable named 'a' and a 'pointer of unsigned int' variable named 'b';
a=20; //assignment of the value 20 to 'a'
b=newunsignedint; //create a new 'unsigned int' in the heap memory and assign its memory address to 'b'
//Now
b = a; //wrong , we can't assign the value of 'a' (unsigned int) to the pointer 'b' (unsigned int *)
*b = a; //fine , we assign the value of 'a' to the deferenced pointer 'b'
b = &a; //fine , we assign the address of 'a' to the pointer 'b'
So, in your code you just modify the linear2 = are; to *ar2 = are
0.k., got it, thank you very much!
But anyway I didn't understood why the * was at the end of the variable name and not at the beginning, not what it meant written before