As it’s probably obvious from my code I’m really new to C language. I’m working on a program which is called from a larger Python program via subprocess.PIPE / cin. My intent was to assign an array of a size directed from Python. Now I realized that I can assign an integer to 1202th block of that array independently of a number I pass to my program. What exactly happens here? Is such array safe to use or is it advisable to use some other feature (I was thinking of vector).
int main()
{
string group_str;
int group_num;
getline (cin, group_str);
stringstream( group_str ) >> group_num;
cout << "Group number" << group_num <<"\n";
int group[ group_num ];
group[ 1202 ] = 233;
for (int i=0; i < 1203 ; i++)
{
cout << group[i] << '\t' << i << endl;
}
return 0;
}
I’d just use C++ STL’s
std::vectorinstead of raw C arrays.#include <vector>and then usestd::vector‘s proper constructor to create a vector of specified size, e.g.Then you can access (read and modify) the vector item at a given index using
operator[], just like with raw C arrays.(If you want bounds checking on the vector index you may consider using
std::vector::at()method, which throws an exception if the vector index is out of bounds.)