samedi 21 novembre 2015

Why does this if-statement not trigger?

One of my coding assignments is asking me to make an insert function for a custom class called LabString. I cannot for the love of me figure out why, when calling the following class function in main:

s1.insert(0, "");

I cannot make it enter the if-statement

if (s[0] == '\0')
    return *this;

I have tried altering it to the following, none of which work for me:

if (s[0] == '\0')
    return *this;

if (s == '\0')
    return *this;

if (s == "")
    return *this;

The last one gives me a warning of unspecified behaviour. I did some Googling but I'm still not sure why.

Here is the full insert function implementation that I have so far:

LabString& LabString::insert(size_t pos, const char *s)
{
    if (s[0] == '\0')
        return *this;

    int i;
    for (i = 0; s[i] != '\0'; i++) {}
    i += this->lengthM;
    char* str = new char(i);

    size_t j;
    for (j = 0; j < pos; j++)
        str[j] = this->storageM[j];

    size_t orig_pos = pos;
    for (int k = 0; s[k] != '\0'; k++, pos++)
        str[pos] = s[k];

    while (this->storageM[orig_pos] != '\0') {
        str[pos] = this->storageM[orig_pos];
        pos++;
        orig_pos++;
    }
    str[pos] = '\0';

    delete [] this->storageM;
    this->storageM = str;
    this->lengthM = pos;
    this->capM = pos+1;

    return *this;
}

Since the if-statement does not get accessed, I get segmentation error. I narrowed it down to this loop (although it really shouldn't get here at all if the if-statement worked properly):

    while (this->storageM[orig_pos] != '\0') {
        str[pos] = this->storageM[orig_pos];
        pos++;
        orig_pos++;
    }

All help is appreciated, thank you in advance!

Aucun commentaire:

Enregistrer un commentaire