two:
Hello. This is a part of my data_structur program. I don't know what I have to do? The func creat have an warning and program doesnot debug.
unitiolizid local variable.
1 2 3 4 5 6
class araye {
int n;
int *data;
public:
int creat (araye , int);
};
1 2 3 4 5
int araye::creat (araye A, int L) {
A.data = newint [L];
A.n = 0;
return 1;
}
1 2 3 4 5 6 7
int main() {
int tedad;
araye *A;
cin>>tedad;
A->creat(*A, tedad);
return 0;
}
You are dereferencing the A pointer before you have made it point to an A object. It doesn't look like you really need it to be a pointer. You could just create it a such araye A;.
Normally constructors are used to initialize objects. Instead of having a creat function you could define a constructor that will initialize the object when it is created. The good thing with using constructors is that you can make sure the object is always in a valid state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class araye {
int n;
int *data;
public:
araye(int);
};
araye::araye(int L) {
data = newint [L];
n = 0;
}
int main() {
int tedad;
cin>>tedad;
araye A(tedad);
return 0;
}
1. I picked the star of A:araye A;
and in main: A.creat(A, tedad);
but does not work. why?
2. Using constructor works properly but new my problem is
1 2 3 4 5 6 7 8 9
int araye::insert(araye A, int m, int L) {
if (A.n==MAX || m>A.n+1)
return 0;
for(int t=A.n;t>m;t--)
A.data[t]=A.data[t-1];
A.data[m-1]=L;
A.n++;
return 1;
}
in visual studio, I foundA.n++causes A.n=1 but when function closes, A.n=0 . why?
A inside the function will be a copy of the araye object that you passed to the function. The function will only modify the copy leaving the original object unchanged. If you want to be able to make changes to the object you pass to the function you should pass a reference or a pointer to the object instead.
In this case however, you don't want to pass the araye object to the function in any way. The function is a member function so it can access the member variables of the object that the function was called on if you just remove the use of A. before the variable names.