I am running the code example for sqlite from here to create a table in C , here is the code:
#include "../contrib/sqlite/sqlite3.h"
static int callback(void* NotUsed, int argc, char** argv, char** azColName) {
int i;
for (i = 0; i < argc; i ) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3* db;
char* zErrMsg = 0;
int rc;
char* sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \ // Error is here at the '='
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
}
But then I get some errors from visual studio 2022 that say:
a value of type "const char *" cannot be assigned to an entity of type "char *"
'=': cannot convert from 'const char [164]' to 'char *'
Does anyone know how to fix this error?
CodePudding user response:
The problem is your sql variable. It is a char* pointer, which is a pointer to non-const character data. But you are trying to assign it to point at a string literal, which is const character data (in this case a const char[164] array). Assigning a non-const character pointer to point at const character data is dangerous, as it allows read-only strings to be mutatable, which is undefined behavior. In C (which the example you are looking at was written for) and old versions of C , such an assignment is legal (albeit not recommended), but in C 11 onward it is illegal.
You need to change the declaration of sql to const char* instead (which is what sqlite3_exec() is expecting anyway).
