0

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;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620

2 Answers2

4

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

Because there is no overload of extracting a pointer from a character stream.

If you want to read into the pointed integer, simply indirect through the pointer:

std::cin >> r.p[i];
sum += r.p[i];

P.S. Avoid using malloc in C++, and avoid owning bare pointers. In this case, std::vector might be a better option.

eerorika
  • 181,943
  • 10
  • 144
  • 256
0

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
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620