[Variable name]*

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>
using namespace std;

int main ()
{
    unsigned int are, wid, hei, *ar2;
    cin >> wid >> hei;
    are = wid * hei;
    ar2 = new unsigned int;
    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>
using namespace std;

int main ()
{
    unsigned int are, wid, hei, *ar2;
    cin >> wid >> hei;
    are = wid * hei;
    ar2 = new unsigned int;
    *ar2 = are; // stores the value in are in the allocated space pointed to by ar2
    delete ar2; // always delete() what you new()
}
Last edited on
@SpamBot
I don't even know what the "*" in "unsigned int*".

Why are you deceiving us? Is it the statement written by you, is not it?

unsigned int are, wid, hei, *ar2;

If you do not know what the '*' means why do you use it?!

The error statement is

ar2 = are;


You shall write

*ar2 = are;
ar2 has the type unsigned int*, which means : a pointer to an unsigned int.
new unsigned int returns unsigned int*.

Read more about pointers here : http://cplusplus.com/doc/tutorial/pointers/

Also you have a little memory leak in your program, since you never delete ar2, but you will understand this more later :)
the '*' symbol means 'pointer of' , then 'unsigned int *' is 'pointer of unsigned int' . when you write unsigned int 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
unsigned int 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=new unsigned int; //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
Last edited on
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
Topic archived. No new replies allowed.