开发者

char to uppercase assignment segmentation fault

In an effort to learn more about the inner wor开发者_开发技巧kings of c++ I decided to write my own string class. However I am stuck on the .toUpper() and .toLower() functions. Here is my code.

Text& toUpper(){
        char* c = this->str;
        while(*c != 0, c++){
            if((*c >= 'a') && (*c <= 'z')){
                *c = *c - 32;                    
                std::cout << *c << std::endl;
            }
        }
        return *this;
    }

I have isolated the line that causes the segmentation fault to *c = *c - 32 but I can't see why this would be causing a problem. I tried (char)(*c - 32) but that didn't work. Also it's not a bounding issue because nothing gets output. Any ideas?

Update: My constructor

Text(char* str){
        this->str = str;
        this->updateLength(); // glorified strlen
    }

My pointer definition

private:
    char* str;
    int len;


while(*c != 0, c++)

The while loop in C++ takes a single expression. It evaluates that expression each iteration to determine whether to continue.

Here, the , is the comma operator, not a separator. The comma operator evaluates the first part (*c != 0), discards the result, then evaluates the second part (c++) and yields that as its result.

Since you kept incrementing c, the condition was never false because c never becomes NULL (note that as written it isn't testing the value pointed-to, it's testing the pointer itself).

Your loop would be cleaner as a for loop:

for (; *c != 0; ++c)


Change your while loop to this:

while(*c != 0){
            if((*c >= 'a') && (*c <= 'z')){
                *c = *c - 32;                    
                std::cout << *c << std::endl;

            }
             c++; // Should be here
        }

See these:

  1. Your code

  2. Edited Code.

From Wiki:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜