Reputation: 799
So I made a struct and I called it inside a function but things are not going well...
the struct is as follows...
STRUCT FUNCTION
struct Line {
private:
int lineNumber;
char lineString[];
public:
bool set(int n,const char* str);
void display() const;
};
Everything is working within the function just fine, I store the lineN and lineS then send them off to the function called... bool set(int n, const char* str); (from above) using a struct named storage. After the first while loop, I used a function named display to...display lol.
SET FUNCTION
void List::set(int no){
Line storage[no];
int i =0, x;
while (i!=no){
cout << "Enter line number : ";
cin >> lineN;
cout << "Enter line string : ";
cin >> lineS;
x = storage[i].set(lineN, lineS);
if (x == 1){
i++;
}
}
i=0;
while (i!=no){
storage[i].display();
i++;
}
}
Besides checking for "true / false", True being any positive integer, False being 0 or negatives integers. I am using the following bool to store numbers (if they are true) inside the storage struct... I think the problem lies here but I cant seem to wrap my head around it...
BOOL FUNCTION
bool Line::set(int n, const char* str){
int i;
if (n >= 1){
lineNumber = n;
for (i=0;i<6;i++){
lineString[i]=str[i];
}
lineString[6]='\0';
return true;
}
else if (n <= 0)
return false;
}
DISPLAY FUNCTION
void Line::display()const{
cout << "LINE: " << lineNumber << " STRING: " << lineString << endl;
}
however, when I hit run the program and lets say I enter 3 times... line number and line string... my result come out as follows...
INPUT:
Enter line number : 3
Enter line string : ABCDEF
Enter line number : 6
Enter line string : YYUTXL
Enter line number : 8
Enter line string : XYXYXX
OUTPUT:
LINE: 3 STRING:
LINE: 6 STRING:
LINE: 8 STRING: XYXYXX
So my question is why is not being stored inside string prior to the last one, if i do this 2 times, only the second one/last one will have strings inside it. I am storing it correctly am I not?
OUTPUT I HOPED FOR:
LINE: 3 STRING: ABCDEF
LINE: 6 STRING: YYUTXL
LINE: 8 STRING: XYXYXX
Upvotes: 0
Views: 556
Reputation:
The trouble is that this is creating an empty array:
char lineString[];
You are not telling it how big to make it, so it is making it zero bytes long. Thus, your attempt to save a six character string is overwriting memory.
You really should use std::string
, but if you don't want to, you at least need to say how big your string is:
char lineString[50]; // save up to 49 characters + NULL.
Upvotes: 5