Reputation: 13
#include<iostream>
using namespace std;
class String {
public:
char *q;
int len;
String() { q = new char[0]; }
String(char * p) {
for (int i = 0;*p!=00; i++) {
len++;
p++;
}
q = new char[len];
for (int i = 0; i < len; i++) {
*q = *p;
p++; q++;
}
for (int i = 0; i < len; i++) {
cout << *q;
q++;
}
}
};
void main() {
String s1;
String s2("My name is navdeep.");
system("PAUSE");
}
Why this is happening i dont knnow, i have tried including cout in the for loop where len is being incremented. there the result is fine. but something goes wrong while copying.
Upvotes: 0
Views: 54
Reputation: 409176
Lets consider these lines for a while:
q = new char[len];
for (int i = 0; i < len; i++) {
*q = *p;
p++; q++;
}
for (int i = 0; i < len; i++) {
cout << *q;
q++;
}
First you allocate memory and assign it to q
.
Then in the first loop you modify q
. and at the end of the loop it will no longer point to the original place, the pointer give to you by the new[]
expression. In fact, q
will be pointing to memory that is not allocated.
You then continue to print out the memory, but now you are out of bounds and will print indeterminate data, leading to undefined behavior.
You loops needs to work on temporary variable, initially initialized to the same value as q
. And you need to reset this temporary pointer between the loops.
Upvotes: 0
Reputation: 1552
You are not resetting the pointers. p and q should point to the beginning of the arrays before each loop.
Upvotes: 1