Search code examples
c++pointersstructure

Is it possible to use "cin" while referring to a pointer in structure?


This code is showing an error at the cin statement. Why is this?

Here is the error:

no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int*')

#include<bits/stdc++.h>
using namespace std;

struct go {
    int size, *p;
} r;

int main()
{
    int sum = 0;
    r.size = 10;
    r.p = (int*) malloc(r.size * sizeof(int));
    for(int i = 0; i < r.size; i++){
        cin >> (r.p + i);   // this line is showing error
        sum = sum + (*(r.p + i));
    }
    cout << sum;
}

Solution

  • std::istream does not have an operator>> to read an int* pointer. That is exactly what the error message is saying.

    What you are really trying to do is read into the individual int elements of the array that you are allocating. That means you need to deference the int* pointer so you can use the operator>> that reads an int value. Just like you dereference the pointer when adding the int values to sum.

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    struct go {
        int size, *p;
    } r;
    
    int main()
    {
        int sum = 0;
    
        r.size = 10;
        r.p = (int*) malloc(r.size * sizeof(int));
        // better: use new[] instead of malloc()
        // better: change r.p from int* to std::vector<int>, then use:
        // r.p.resize(r.size);
    
        for(int i = 0; i < r.size; i++){
            cin >> *(r.p + i); // or: cin >> r.p[i];
            sum += *(r.p + i); // or: sum += r.p[i];
        }
    
        cout << sum;
    
        free(r.p);
        // better: use delete[] instead of free()
        // better: let std::vector free the memory for you
    }