简体   繁体   中英

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. 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 . 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.

Also, the varchar2 structure array only contains a single element, which can't hold any non-empty null-terminated byte string.

To solve your problems you need to use pointers, flexible array member and dynamic allocation using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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