Navdeep Kumar
Navdeep Kumar

Reputation: 13

Trying to initialize String class via constructor.I am getting weird output

#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");  
}      

enter image description here

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

Answers (2)

Some programmer dude
Some programmer dude

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

perencia
perencia

Reputation: 1552

You are not resetting the pointers. p and q should point to the beginning of the arrays before each loop.

Upvotes: 1

Related Questions