Using char* with sprintf

Hi everyone,

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?
q is an uninitialized char pointer (not a string), so what do you expect?
For string operations, std::string is used in C++.
In doing this...

 
char * q;


you are declaring q as pointing to a memory location where a string is stored.

But you never assigned a legal memory address to it. It could be pointing anywhere in your computer's RAM.

You need to ask the system for a chunk of memory and assign its address to your variable q:


 
char * q = new char[100]; // request 100 chars and store the address of the first one in q. 

Last edited on
Its much better to use std::string to store strings.

http://www.cplusplus.com/reference/string/

1
2
3
4
5
#include <string>

std::string q;

q = "This is my string";

Hi,

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*)
You can convert a std::string to a C-style string when needed by calling the c_str() member function.
1
2
3
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.
Last edited on
Topic archived. No new replies allowed.