0 c++ crash runtime-error sizeof
这只是一个基本的打印句子数组字符串.我是c ++的新手,只使用过JAVA和类似的语言.尝试通过遍历每种不同的排序算法和数据结构来学习它.
但在我开始之前,只测试我的字符串数组会给我一个错误.我不知道为什么它会给我一个错误.实际编译运行良好并打印意图内容,但如果您正在调试它则会崩溃并出现错误.任何人都可以向我解释为什么会这样.尝试size()并length()从C++库,但不得不使用sizeof()
//BubbleSort.cpp
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
string something[14];
something[0] = "Kate";
something[1] = "likes";
something[2] = "lots";
something[3] = "of";
something[4] = "cake";
something[5] = "in";
something[6] = "her";
something[7] = "mouth";
something[8] = "and";
something[9] = "will";
something[10] = "pay";
something[11] = "a";
something[12] = "lot";
something[13] = "lol";
int some = sizeof(something);
some--;
for (int i = 0; i < some; i++)
{
cout << something[i] << " " ;
}
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
sizeof(something)不会像预期的那样返回14,但它会返回,sizeof(string)*14因此当您尝试打印时遇到缓冲区溢出.你需要的是什么
some = sizeof(something)/sizeof(string)
Run Code Online (Sandbox Code Playgroud)
或者@Tiago提到你可以使用
some = sizeof(something)/sizeof(something[0])
同样@James建议你应该调查一下std:vector.
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |