#include <iostream>
using namespace std;
int main() {
int* nbGround = nullptr;
int* nbTrades = nullptr;
int* nbSpace = nullptr;
nbGround = new int(24);
nbTrades = new int(31);
nbSpace = *nbTrades *nbGround;
cout << "Number of spaces for sale : " << *nbSpace << endl;
delete nbSpace;
delete nbTrades;
delete nbGround;
I would like to know why can't I add pointers? I would like nbSpace
to be equal to 55 by using pointers, but I don't know how. I'm getting the error:
incompatible integer to pointer conversion assigning to 'int *' from 'int'
CodePudding user response:
First, this:
*nbTrades *nbGround
is not "adding pointers". Instead, two pointers are dereferenced and two int
s are added.
Then, you try to assign the result (an int
) to a pointer:
nbSpace = *nbTrades *nbGround;
That doesn't make sense. Probably you forgot another *
:
*nbSpace = *nbTrades *nbGround;
This would dereference all three pointers, add two int
s and assign the result to an int
. I say "would", because *nbSpace
is undefined, because it is just a pointer that does not point to a valid int
.
I suppose this is just to practice, because there is no reason to use any pointer here. This is how your code can be made to work with minimal changes:
#include <iostream>
int main() {
int* nbGround = new int(24);
int* nbTrades = new int(31);
int* nbSpace = new int(0);
*nbSpace = *nbTrades *nbGround;
std::cout << "Number of spaces for sale : " << *nbSpace << std::endl;
delete nbSpace;
delete nbTrades;
delete nbGround;
}
CodePudding user response:
#include <iostream>
using namespace std;
int main() {
int* nbGround = nullptr;
int* nbTrades = nullptr;
int nbSpace;
nbGround = new int(24);
nbTrades = new int(31);
nbSpace = *nbTrades *nbGround;
cout << "Number of spaces for sale : " << nbSpace << endl;
delete nbTrades;
delete nbGround;
}
It's unclear why you need pointers here at all, but the error you get is caused by trying to assign an int (the result of the addition) to an int pointer. If you make it a regular int (with some required modifications to the rest of the code), it runs fine. Once again, it doesn't look like you need pointers at all in this code.
CodePudding user response:
You need to store the result in the integer being pointed by nbSpace like this:
// first allocate space for the result
nbSpace = new int(0);
*nbSpace = *nbTrades *nbGround;
Otherwise, you're setting the value of the pointer to the sum of the integers. In other words, nbSpace
refers to the pointer, and *nbSpace
refers to the integer value being pointed by nbSpace
.