简体   繁体   English

访问另一个结构中的'typedef struct with char array'

[英]accessing a 'typedef struct with char array' inside another structure

The objective I am trying to meet is to build a structure to read and write Oracle VARCHAR2 data type.我试图实现的目标是构建一个结构来读取和写入 Oracle VARCHAR2 数据类型。 from and to database.从和到数据库。 Hence I made a C structure as specified by Oracle and try to write data to variable, which I am unable to .因此,我制作了一个由 Oracle 指定的 C 结构,并尝试将数据写入变量,但我无法做到。 I try in two different ways, they give different arrays.我尝试了两种不同的方式,它们给出了不同的数组。 Could someone please tell me what I am doing wrong here, and way to correct it to meet my objective.有人可以告诉我我在这里做错了什么,以及纠正它以实现我的目标的方法。

#include<stdio.h>
#include<string.h>

typedef struct { unsigned short len; unsigned char arr[1]; } varchar2;

struct teststruct
{
        varchar2 name[20];
};

void main()
{
    struct teststruct obj;

    //error: request for member ‘arr’ in something not a structure or union
    strcpy( obj.name.arr, "adarsh" );

    //trying like this..
    //warning: initialization from incompatible pointer type [enabled by default]       
    struct varchar2 *ptr = ( varchar2* ) obj.name;
    //error: dereferencing pointer to incomplete type
    strcpy( ptr->arr, "name" );

}

What you want to do is not possible, for several reasons.由于多种原因,您想要做的事情是不可能的。

For starters, the name member of the teststruct structure is an array of 20 varchar2 structures, not a single varchar2 structure that contains space for 20 characters.首先, teststruct结构的name成员是一个包含20 varchar2结构的数组,而不是包含20字符空间的单个varchar2结构。

Also, the varchar2 structure array only contains a single element, which can't hold any non-empty null-terminated byte string.此外, varchar2结构数组只包含一个元素,不能保存任何非空的空终止字节字符串。

To solve your problems you need to use pointers, flexible array member and dynamic allocation using malloc .要解决您的问题,您需要使用指针、灵活的数组成员和使用malloc动态分配。

Then you could have something like然后你可以有类似的东西

typedef struct
{
    unsigned short len;

    // Last member being an array without a size makes it a flexible array member
    unsigned char arr[];
} varchar2;

struct teststruct
{
    varchar2 *name;
};

varchar2 *create_varchar2(unsigned short length)
{
    // Size of the structure itself, plus the size of the string,
    // plus one for the null-terminator
    varchar2 *string = malloc(sizeof *string + length + 1);

    // TODO: Check for failure and handle it in some way

    string->len = length;
    return string;
}

varchar2 *create_varchar2_string(const char *str)
{
    varchar2 *string = create_varchar2(strlen(str));

    strcpy(string->arr, str);

    return string;
}

int main(void)
{
    teststruct obj;
    obj.name = create_varchar2_string("hello");
    printf("name = %s\n", obj.name->arr);
}

You can then add functions to modify the "string", including changing its size.然后,您可以添加函数来修改“字符串”,包括更改其大小。

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

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