I am trying to pass a dynamic string into sprintf, so I don't have to use a fixed char array, like this:
1 2
char * q;
sprintf(q,"This is my string and my vars: "%d",x);
The program gives an illegal operation at runtime, and closes. It works fine when I declare q as char [256] instead of char *. Any idea why this happens?
Sorry for the long time it took me to reply. The reason I'm not using std::string is because I want to use the SQLite library, which only accepts char * for the most commonly used functions. So far I've been able to use sqlite3_prepare (which takes a char * for the SQL query text) by using a large char[] (specifically, char [1024]), since I don't know how long the query will be.
I do something like this:
1 2
char query[1024];
sprintf(query, "Delete from Contacts where id = %d ;",id);
I don't like this design, as it put constraints on what can be entered (not to mention it consumes more memory. can you suggest an alternative way to do this? (Note: The variable needs to be char*)
stringstream query;
query << "Delete from Contacts where id = '" << id << "';";
// try using: query.str().c_str()
You may have to copy the string from the stream and keep it around while doing the calls with the library... I'm not aware of its implementation--it might copy the string or it might expect it to be in scope until after the call.