khan
khan

Reputation: 9

char array displaying garbage after instantiation using new

I am try to concatenate the following 4 things to an char array(in C++) so i can return my array but along with those 4 things i am also getting garbage in my array. can anyone kindly help

char* Guest::toString()
{

    char * p = new char[30];

    p[0] = firstName[0];
    p[1] = '.';
    p[2]=lastName[0];
    p[3] = '.';
        return p;
}

Upvotes: 0

Views: 34

Answers (1)

Gregory Noma
Gregory Noma

Reputation: 21

The elements of an array are uninitialized upon creation, so in your case everything past p[3] is still uninitialized. Attempting to access these uninitialized elements will result in undefined behavior, which is why you're getting garbage data.

I believe that you can initialize it by using:

char * p = new char[30]();

Upvotes: 2

Related Questions