Reputation: 59
I use visual studio 2012 and when i tried to build this simple program i receive this error and i can't understand where is the problem. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#define MAXN 400 //max digits
using namespace std;
typedef struct {
//signbit nqma nujda v tozi slu4ai
char digits[MAXN];
int lastdigit;
} BigInteger;
BigInteger addBigIntegers(BigInteger *a, BigInteger *b, BigInteger *c)
{
c->lastdigit = max(a->lastdigit, b->lastdigit);
int carry = 0;
for(int i = 0; i<=(c->lastdigit); i++)
{
c->digits[i] = (char)(carry + a->digits[i] + b->digits[i]) % 10;
carry = (carry + a->digits[i] + b->digits[i]) / 10;
}
return *c;
}
int main()
{
BigInteger a;
BigInteger b;
string input1;
string input2;
cin >> input1 >> input2;
int len1 = input1.length();
int len2 = input2.length();
for(int i = len1-1; i>=0; i--)
{
a->digits[i] = 5;
}
}
The error is on this line:
a->digits[i] = 5;
How can i fix it?
Upvotes: 3
Views: 16955
Reputation: 335
In C++, object->member
is syntactic sugar for (*object).member
. That is, it dereferences object
before attempting to access member
. The dereferencing operator *
can only be applied to pointer types.
N.B. There are exceptions to this - if object
is an instance of a class which overloads either *
or ->
, these operators will perform their function as defined in the class. In this case, it is possible to apply these operators to non-pointer objects.
In general, if you want to access a member of a struct or class, use object.member
. If you have a pointer to a struct or class, use (*pointer).member
, or the shorter pointer->member
.
Also, typedef struct
is more C than C++. It is more usual to simply declare as struct
in C++. So the BigInteger
declaration would become:
struct BigInteger {
char digits[MAXN];
int lastdigit;
};
A struct
in C++ is just a class where all members are public
by default.
Upvotes: 5