I have a class defined as,
class dimension{
public:
dimension();
const char* getname();
long ing getlength();
void setname(const char* text)
void setlength(long int size)
virtual ~dimension();
private:
const char* name;
long int length;
}
I am getting error regarding the functions setname
and setlength
are of importance so their definitions are as,
void dimension::setname(const char* text)
{
dimension::name = text;
}
void dimension::setlength(long int size)
{
dimension::length = size;
}
Now i have 2 functions which i am using to read an array of objects of class dimension from a file. Their definition is as.
void read_dimension(dimension** dims, int*ndims, const char* text, long int size)
{
int i;
*dims = new dimension[*ndims];
for(i=0; i<ndims; i++)
{
(*dims)[i].setname(text)
(*dims)[i].setlength(size)
}
}
void read_file(char *path, dimension** dims, int *ndims)
{
//do-- open file and read the variables ndims, text and size from it.
read_dimension(dims, ndims, text, size);
//do-- print name and length of all elements of (*dims).
}
Now, i am calling these functions in main as
int main()
{
//do-- get file path
dimesnion* gdims;
int num_dims;
read_file(path, &gdims, &num_dims);
//do-- print name and length of each element of gdims.
return 0;
}
When i run the code the variable "name"
printed from the the functions read_dimension()
and main()
are different but the variable "length"
is the same.
I can't figure out why this is happening.
I would be glad if anyone could help.
There's no doubts text is a local variable in read_dimension function, probably an array of char. dimension::setname assigns one pointer to another, as already mentioned, what happens when text variable in read_dimension function goes out of scope? It'll die... Now your pointer in dimension class points to "nowhere". I prefer to use const char * as string literals or as pointer to some char in array of chars. If you want to store a string you'd copy it via strcpy maybe, of course destination array of char with sufficient space must exists.
What's the purpose of this code: dimension::name = text; and dimension::length = size; in setname and setlength methods? You're in the scope of dimension class, aren't you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.