简体   繁体   English

C++ 堆栈溢出是什么原因造成的?

[英]C++ Stack Overflow what is causing it?

I am new to C++ and wrote the following:我是 C++ 的新手,并写了以下内容:

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> result(n);
        for (int i=1;i<=n;++i)
        {
            if (i%3==0 and i%5==0)
                result[i-1]="FizzBuzz";
            else if (i%3==0)
                result[i-1]="Fizz";
            else if (i%5==0)
                result[i-1]="Buzz";
            else result[i-1]=""+i;
        }
        return result;
    }
};

when the input is 1 I am getting overflow error, why is that?当输入为 1 时出现溢出错误,这是为什么呢? the last line seems the problem but I think it's totally fine.最后一行似乎是问题,但我认为这完全没问题。

The expression ""+i doesn't convert the integer value in i to a string.表达式""+i不会将i中的 integer 值转换为字符串。 Instead it's the same as &(("")[i]) .相反,它与&(("")[i])相同。 Ie it's a pointer to the i:th value of the string "" .即它是指向字符串""的第 i:th 值的指针。 Which is out of bounds since the empty string only have a single element at index 0 (the string terminator).这是超出范围的,因为空字符串在索引0 (字符串终止符)处只有一个元素。

Usestd::to_string instead:改用std::to_string

result[i-1]=std::to_string(i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM