This is just a basic print a sentence array string. I am new to c++ only used JAVA and similar languages never c before. Trying to learn it by going through every different sort algorithm and data structure.
But before I could get started just testing my string array would give me an error. I have no idea why it is giving me a error. Compiles fine in fact runs and prints the intend content but crashes with a error if you are debugging it. Can anyone explain to me as to why that is. Tried size() and length() from c++ library but had to use 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;
}
sizeof(something)would not return 14 as you expect , but it returnssizeof(string)*14so you are encountering a buffer overflow when you try to print .What you need is
or as mentioned by @Tiago you could use
some = sizeof(something)/sizeof(something[0])Also as @James suggested you should look into
std:vector.