This is the program:
#include <QPoint>
#include <string.h>
#include <QList>
using namespace std;
#include <iostream>
int main(int argc, char *argv[])
{
int y = 14;
char * str = new char [y];
str = "23,211,23,211";
char *pch;
std::cout << "\nSplitting string into tokens: \n" << str;
pch = strtok (str,",");
QList <int> p;
while (pch != NULL)
{
std::cout << "\npch:" << pch;
p.push_back (atoi (pch));
pch = strtok (NULL, ",");
}
std::cout << "Length of p " << p.length() << std::endl;
QPoint first;
first.setX (p[0]);
first.setY (p[1]);
QPoint second;
second.setX (p[2]);
second.setY (p[3]);
return 0;
}
The output is:
What point am I missing?
There are several bugs in your code. First of all there is a memory leak. At first you allocated dynamically memory and its address was assigned to pointer
str
And then you reassigned the pointer with the address of string literal
"23,211,23,211"
So the address of the allocated memory is lost.
String literals may not be modified neither in C++ nor in C while function
strtok
tries to change the string passed to it as an argument. So the program has undefined behaviour.I think you mean the following.
Also in general case the length of
p
can be equal to zero. So you may not use the subscript operator withp
without checking that it has a non-zero length.Instead of C function
strtok
you could use string streamstd::istringstream
declared in header<sstream>
.Take into account that you should use header
<cstring>
instead of<string.h>
in C++.