将 sqlite3_column_text() 返回到文字字符串

Cro*_*oad 2 c sqlite string pointers literals

我有以下疑问:

考虑从 sqlite 数据库中对下表进行 SELECT:

id | label
1  | P1
1  | P2
1  | P3
1  | P4
Run Code Online (Sandbox Code Playgroud)

我运行以下测试代码:

const unsigned char * new1;
const unsigned char * new2;
const unsigned char * new3;
const unsigned char * new4;

sqlite3_step(stmt);
new1=sqlite3_column_text(stmt,1);

sqlite3_step(stmt);
new2=sqlite3_column_text(stmt,1);

sqlite3_step(stmt);
new3=sqlite3_column_text(stmt,1);

sqlite3_step(stmt);
new4=sqlite3_column_text(stmt,1);

printf("%s\n%s\n%s\n%s\n",new1,new2,new3,new4);
printf("%p\n%p\n%p\n%p\n",new1,new2,new3,new4);
Run Code Online (Sandbox Code Playgroud)

我得到:

P4
P4
P4
P4
0x1d5b7f8
0x1d5b7f8
0x1d5b7f8
0x1d5b7f8
Run Code Online (Sandbox Code Playgroud)

我要打印

P1
P2
P3
P4
Address1
Address2
Address3
Address4
Run Code Online (Sandbox Code Playgroud)

有什么方法可以仅使用字符串文字来打印此内容,而不使用 buffer const char value[N];、strcpy 等...?

小智 5

返回的指针一直有效,直到发生如上所述的类型转换,或者直到调用 sqlite3_step() 或 sqlite3_reset() 或 sqlite3_finalize() 为止。用于保存字符串和 BLOB 的内存空间会自动释放。

除非您printf在每次之后sqlite3_column_text(地址仍然相同),否则您需要复印。