Using pointer in function. Error int *width, int *height.

Hi! I would like to know whats the problem of my code.
It can't read *width and *height
Thank youuu.

#include <iostream>

using namespace std;

void getd (int *width, int *height){
cin *width;
cin *height; }

int main (){
int w=0, h=0, area=-1;
int *pl, *p2;
getd (pl, p2);
area=w*h;
cout <<area;

return 0;
}

cin statement is wrong.

cin looks like

cin >> variable;
for a pointer, that just becomes cin >> variable[0]; or if you insist cin >> *variable;

you call getd with pl and p2, but area is w(zero)*h(zero) which is zero.

did you mean
getd(&w, &h); ???

what is the purpose of pl and p2?

why are you using pointers at all??

@jonnin
Thanks for ur reply :) becuz my lecturer used this as an example.

How bout this ?

#include <iostream>

using namespace std;

void getd (int *width, int *height){
cin *width;
cin *height; }

int main (){
int w=0, h=0, area=-1;
getd (&w, &h);
area=w*h;
cout <<area;

return 0;
}

But i still get problem in cin *width.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

// Passing variables by "reference" the C way.
void getd(int *width, int *height) {
    cout << "Enter width and height: ";
    cin >> *width >> *height;
}

// How it's done in C++.
void getd2(int &width, int &height) {
    cout << "Enter width and height: ";
    cin >> width >> height;
}

int main() {
    int w = 0, h = 0, area = -1;

    // How it's called in the C-style pointer version (need to pass addresses).
    getd(&w, &h);
    area = w * h;
    cout << area << '\n';

    // How it's called in C++ reference version.
    getd2(w, h);
    area = w * h;
    cout << area << '\n';

    return 0;
}

Last edited on
Oh shxt.... i get it im stupid
I MISSED THE >>, CIN >> ......
I SPENT AN HOUR LOL
Last edited on
You also tried to use two uninitialized pointers and expected data to magically appear in w and h.
Registered users can post here. Sign in or register to post.