簡體   English   中英

C基礎知識,指向指針的字符串

[英]C basics, string to pointer

我有3個文件的項目。 通用頭包含用於檢查mysql連接的函數聲明:

int conn_check(char **m_error);

主文件調用函數,並在出現錯誤的情況下在m_error中期待一些消息:

if (!conn_check(&m_error)==0)
{
 printf("%s\n", m_error);
}

現在由於缺乏對指針的了解,我遇到了問題:

int conn_check(char **m_error)
{
int retval = 0;
char mysqlerror[255] = {0};
MYSQL *conn;
conn = mysql_init(NULL);
if (conn)
{
    if (mysql_real_connect(conn, mysql_server, mysql_user_name, mysql_password, "", (ulong)mysql_serverport, mysql_socket, 0)==NULL)
    {
        sprintf(mysqlerror, "%u: %s", mysql_errno(conn), mysql_error(conn));
        *m_error = mysqlerror;  // Problem here
        retval = -1;
    }
} else retval = -2;
mysql_close(conn);
return retval;
}

問題是如何正確地將字符串mysqlerror分配給char指針m_error,以便可以通過main中的printf打印錯誤消息。

char **m_error表示您正在將指針傳遞給指針。 大概是因為該函數已經返回了一個int並且您還希望包含錯誤的文本。 實際上,您正在將堆棧變量的地址分配給無法執行的指針。

您將需要分配內存,將其分配給指針,然后寫入:

*m_error = calloc(255, sizeof(char));
snprintf(*m_error, 255, "%u: %s", mysql_errno(conn), mysql_error(conn));

vasprintf()將為您完成所有操作:

vasprintf(m_error, "%u: %s", mysql_errno(conn), mysql_error(conn));

請注意,然后您需要將free()回調用函數中。

您正在返回一個指向局部變量的指針(char mysqlerror [255])。 您應該在主文件中定義mysqlerror,然后像下面這樣調用函數:

 if (!conn_check(mysqlerror)==0)

並更改原型:

int conn_check(char *mysqlerror)

並刪除行:

 char mysqlerror[255] = {0};
 *m_error = mysqlerror;

conn_check()返回時,如果執行*m_error = mysqlerror; 一行,到那時,您將得到一個很可能無效的指針,因為本地char數組mysqlerror在本地函數外部無效。

您需要傳遞一個指向緩沖區的指針並復制該字符串,或者使用strdup復制該字符串以分配一些全局內存,以便為您提供有效的返回指針(但是,如果這樣做,請不要忘記釋放該指針) main()的內存,之后使用free )。

編輯:如果選擇傳遞緩沖區,則傳遞最大緩沖區大小也是一種好習慣,因此,當您復制字符串時,不會溢出緩沖區。

編輯2:用最少的代碼修復現有代碼的一種非常怪誕的方法當然是將mysqlerror聲明為靜態,因此在函數外部有效。 我永遠不建議這樣做,因為這意味着該函數不是線程安全的。

這是我的解決方案:

char m_error[255];
if (!conn_check(&m_error)==0)
{
 printf("%s\n", m_error);
}

int conn_check(char **m_error)
{
    int retval = 0;
    char mysqlerror[255];
    MYSQL *conn;
    ...
    sprintf(mysqlerror, "%u: %s", mysql_errno(conn), mysql_error(conn));
    strcopy(*m_error, mysqlerror);
    retval = -1;
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM