简体   繁体   English

无法访问嵌套结构的值

[英]Unable to access values from nested structs

I have been working on some C code which is not mine and in the process learning C too. 我一直在研究不是我的C代码,并且也在学习C。 But the code I am stuck right now is little too much for me. 但是我现在停留的代码对我来说太少了。 I know this would be a trivial question for experts here. 我知道这对于这里的专家来说是一个微不足道的问题。 What I have is nested structures and I need to assign values to it. 我拥有的是嵌套结构,我需要为其赋值。 Below is the code: 下面是代码:

The Structs: 结构:

struct _str{
    char* s; /**< string as char array */
    int len; /**< string length, not including null-termination */
};

typedef struct _str str;
typedef str* db_key_t;

typedef enum {
    DB_INT,        /**< represents an 32 bit integer number      */
    DB_BIGINT,     /**< represents an 64 bit integer number      */
    DB_DOUBLE,     /**< represents a floating point number       */
    DB_STRING,     /**< represents a zero terminated const char* */
    DB_STR,        /**< represents a string of 'str' type        */
    DB_DATETIME,   /**< represents date and time                 */
    DB_BLOB,       /**< represents a large binary object         */
    DB_BITMAP      /**< an one-dimensional array of 32 flags     */
} db_type_t;


typedef struct {
    db_type_t type; /**< Type of the value                              */
    int nul;        /**< Means that the column in database has no value */
    int free;       /**< Means that the value should be freed */
    /** Column value structure that holds the actual data in a union.  */
    union {
        int           int_val;    /**< integer value              */
        long long     bigint_val; /**< big integer value          */
        double        double_val; /**< double value               */
        time_t        time_val;   /**< unix time_t value          */
        const char*   string_val; /**< zero terminated string     */
        str           str_val;    /**< str type string value      */
        str           blob_val;   /**< binary object data         */
        unsigned int  bitmap_val; /**< Bitmap data type           */
    } val;
} db_val_t;
typedef struct db_row {
    db_val_t* values;  /**< Columns in the row */
    int n;             /**< Number of columns in the row */
} db_row_t;
struct db_row;
typedef struct db_res {
    struct {
        db_key_t* names;   /**< Column names                    */
        db_type_t* types;  /**< Column types                    */
        int n;             /**< Number of columns               */
    } col;
    struct db_row* rows;   /**< Rows                            */
    int n;                 /**< Number of rows in current fetch */
    int res_rows;          /**< Number of total rows in query   */
    int last_row;          /**< Last row                        */
} db_res_t;

The Sample code what I am doing to understand: 我正在理解的示例代码:

    #include "Util.h"
    #include "cJSON.h"
    int main(void)
    {
        char *json = "[{\"domain\":\"192.168.254.1\",\"username\":\"user1\",\"expires\":123},{\"domain\":\"192.168.254.2\",\"username\":\"user2\",\"expires\":123}]";


    db_res_t *result = NULL;
    int i=0;

    i = parse_json_to_result(json, &result);
 ** I think accessing like below is fine, as we have pointer structs and val is not pointer so '.' **
    printf("result0: %d",result->rows->values->val.int_val);
    printf("result1: %d",result->rows->values->val.int_val);
     return 1;
    }

    int parse_json_to_result(char *json, db_res_t** result)
    {
        cJSON *root,*record;
        int recourdCount = 0;
        int i=0;
        int value=0;

        root =cJSON_Parse(json);
        recourdCount= cJSON_GetArraySize(root);
        printf("array size: %d\n",recourdCount);

        for(i=0;i<recourdCount;i++)
        {
            record = cJSON_GetArrayItem(root, i);
            value =  cJSON_GetObjectItem(record,"expires")->valueint;
            printf("Fetched value: %d\n",value);
** The below line gives segmentation fault**
            ((*result)->rows->values)->val.int_val = value;
        }
    return 1;
    }

I want to assign values to the struct and doing as below: 我想给结构赋值,并做如下操作:

    ((*result)->rows->values)->val.int_val = value;

result is pointer to pointer, so first I dereference it then rest are pointer to structures so using '->' and val is just struct so '.' 结果是指向指针的指针,所以首先我取消引用它,然后其余部分指向结构的指针,因此使用'->'和val只是结构,所以'。'。

*result->rows->values->val.int_val = value;

When I wrote as above I was getting compilation errors like row is not struct or union and same for val. 当我如上所述编写时,我遇到了诸如row不是struct或union以及val相同的编译错误。

I need little help in understanding how to assign values to this long chain of structs. 在了解如何将值分配给此长链结构时,我几乎不需要帮助。

Also, one thing I am not able to understand is that in the code on which I am working, the rows are accessed as rows[0], rows[1] but I do not see array declaration in the structs. 另外,我无法理解的一件事是,在我正在处理的代码中,行以rows [0],rows [1]的形式访问,但在结构中看不到数组声明。 How can I create the array of rows? 如何创建行数组?

Thanks 谢谢

Firstly, the commenter is right that you need to initialize your result pointer. 首先,注释器正确,您需要初始化结果指针。 If it's just pointing to NULL, of course you are going to segfault. 如果它只是指向NULL,那么您当然要进行segfault。

So let's make our result point to some allocated memory 因此,让我们将结果指向一些已分配的内存

db_res_t *result = malloc(sizeof(db_res_it));

But we are not done. 但是我们还没有完成。 Notice that result->rows is a pointer to another struct. 注意,result-> rows是指向另一个结构的指针。 Even though we malloc'd space for the result struct, it only allocated memory for the POINTER to the db_row struct, NOT for the db_row struct itself. 即使我们为结果结构分配了空间,它也只为POINTER分配了内存给db_row结构,而不为db_row结构本身分配了内存。 So we need to make sure that the rows pointer is also initialized. 因此,我们需要确保行指针也已初始化。

result->rows = malloc(sizeof(db_row_t));

Now the same thing happens again with the values field in db_row. 现在,db_row中的values字段再次发生相同的事情。

result->rows->values = malloc(sizeof(db_val_t));

After I added these three lines to your program and commenting out the function calls that aren't provided in your original post, I got your program to run without segfaulting. 在将这三行添加到您的程序中并注释掉了原始帖子中未提供的函数调用之后,我使您的程序可以运行而不会出现段错误。

As for your other question, about accessing the row as array: In C, this is basically a pointer. 至于另一个问题,关于将行作为数组访问:在C语言中,这基本上是一个指针。 Hanno Binder provides a good resource for you to follow; Hanno Binder为您提供了很好的参考资源; this is a important and fundamnetal concept of C to understand. 这是C要理解的重要且基本的概念。

Good luck on your learning journey! 祝您学习愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM