传递给函数的结构中的数组的C指针

时间:2016-06-17 10:48:21

标签: c arrays pointers

我试图将一个指向数组的指针传递给一个sqlite3操作的回调函数。不幸的是,我对指针的理解(显然缺少某些东西)产生的逻辑不起作用。

简化,这就是我所拥有的:

    typedef struct sqlCallbackData
    {
        int16_t data_array[128][32];

        // There are other members here too...

    } SqlCallbackData_t;

    //===========================================================================================================
    //===========================================================================================================

    void sql_getData(uint8_t seq_num, uint8_t seq_bank, int16_t *data, char *name)
    {
        // 'data' above will be a pointer to a 2D array

        //...

        // Initialise struct members to be passed into callback...
        SqlCallbackData_t paramStruct;

        //Thows: error: incompatible types when assigning to type 'int16_t[128][32]' from type 'int16_t *'
        paramStruct.data_array = data;// I know this isn't right...

        //...

        // Pointer to paramStruct passed into void pointer in callback...
        if (sqlite3_exec(dbPtr, sql, callback, &paramStruct, &zErrMsg) != SQLITE_OK)
        {
            fprintf (stderr, "SQL error: %s\r\n", zErrMsg);
            sqlite3_free(zErrMsg);
        }

        //...
    }

    //===========================================================================================================
    //===========================================================================================================
    // Callback function

    static int load_callback(void *paramStruct, int argc, char **argv, char **azColName)
    {
        int i;

        uint8_t value;

        //...

        // Just making the syntax below a bit mroe readable, as I access members a fair bit in this function
        SqlCallbackData_t *params = ((SqlCallbackData_t *)paramStruct);

        //...
        // Data retreived from sql database...

        params->data_array[0][0] = value;// <- What I'm trying to acheive...obviosuly not correct

        return 0;
    }

所以我知道如何将指向数组的指针传递给函数(解释here),但是我对如何将这个指针指向数组分配到一个结构中感到困惑,将其传递给函数(然后再次作为数组访问。)

围成一圈,所以任何帮助都会非常感激:)

2 个答案:

答案 0 :(得分:0)

  

我试图在结构

中传递指向数组的指针

为此您需要像这样更改结构,请查看two dimensional array pointer

typedef struct sqlCallbackData
{
     int16_t (*data_array)[32]; //2d array pointer

    // There are other members here too...

} SqlCallbackData_t;

为指针分配地址时......

void sql_getData(uint8_t seq_num, uint8_t seq_bank, int16_t (*data)[32], char *name)
    {
        // 'data' above will be a pointer to a 2D array
        // Initialise struct members to be passed into callback...
        SqlCallbackData_t paramStruct;

        paramStruct.data_array = data;

答案 1 :(得分:0)

假设数据总是足以填满整个data_array:

memcpy(paramStruct.data_array, data, sizeof(paramStruct.data_array))

否则,请注意尽可能多地复制实际数据,而不仅仅是sizeof(整个数组)。

声明的数组不是指针,它是结构的一部分。 该结构至少有8KB长。