Question

I am trying to create unique primary IDs for my SQLite database by casting a static integer as a character that then is included in my SQL command.

My code is:

/*Global Variables*/
static int ID = 1;
sqlite3 *db;//pointer to db
char *zErrMsg = 0;//initialize 
int rc = sqlite3_open("database.db", &db);//open connection;

int main(){
   char str[150];
   char userName[9]; char password[9]; char ip[9];
   char uniqID = (char)('0'+(int)ID);
   printf("Enter username: "); gets(userName);
   printf("Enter password: "); gets(password);
   printf("Enter IP: "); gets(ip);

   strcpy(str, "INSERT INTO USERS (ID,USERNAME,PASSWORD,IP) "  \
            "VALUES (");
   strcat(str, uniqID);
   strcat(str, ", '");
   strcat(str, user);
   strcat(str, "', '");
   strcat(str, password);
   strcat(str, "', '");
   strcat(str, ip);
   strcat(str, "');");

   rc = sqlite3_exec(db, str, callback, 0, &zErrMsg);
   (rc != SQLITE_OK) ? fprintf(stderr, "SQL error: %s\n", zErrMsg) : fprintf(stdout, "Records created successfully\n");
   ID++;
}

This would be a function later so that when the function would be called uniqID would be incremented by 1 to become a new primary key for each new entry into my table.

The error that I am getting pertains to strcat(str, uniqID); and is throwing incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with &[-Wint-conversion]

Printing the character is fine, but concatenating it with the rest of the string is where I am running into difficulties. What can I do to solve this issue?

What I don't understand is that although the value of uniqID is reliant on ID, once uniqID is declared, if ID changes, the changes do not impact the character uniqID (it does not dynamically change with the value of ID) because it is retaining its prior value. Because of this I figured uniqID is just assigned the ASCII value of ID when it is assigned.

Was it helpful?

Solution

strcat expects a null-terminated string. You need to take the integer and convert it to a null-terminated string via the itoa function.

Essentially the way your code reads right now is you're adding the value of the character 0 in ASCII to your ID and then casting the whole thing to a char and then passing that as the address (since it thinks it's a pointer) to the strcat function.

As an aside, using gets to collect data that is a fixed length (e.g., your username is of length 9) is a recipe for buffer overflows. I recommend using fgets because it allows you to pass in a buffer length.

OTHER TIPS

Keep in mind that ID will return to '1' every time the program is executed.

static int ID = 1;


   char uniqID = (char)('0'+(int)ID);        //  Remove this line.

      strcat(str, uniqID);                   // <-- Change this line to
      snprintf(&str[strlen(str)], "%d", ID); // <-- to this line.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top