开发者

g_strduping a char array member element

开发者 https://www.devze.com 2022-12-17 03:12 出处:网络
typedef struct { char name[10]; } A; A * inst = get_instance_of_A(); char *str = g_strdup ( inst->name );
typedef struct {
char name[10];
} A;
A * inst = get_instance_of_A();
char *str = g_strdup ( inst->name );

The last line doesn't compile. I also tried &(inst->name) with no luck. The error I get is:

Error: char is not a structure type.

I understand that char[] and char * are different types altogether. But shouldn't g_strdup be able to take a starting position of a C string and dupe it? If I do the following it works:

char temp[10];
strncpy(temp,inst->name,9);
char *str = g_strdup ( temp );

How can I achieve what I am trying to do without making a local char array copy? I think I am not passing the argument correctly in the fist scenario as in both cases g_strdup is being pass开发者_开发问答ed a char array.


I don't think your problem lies where you think it does. gchar and char are for all intents and purposes the same. For example, this code works fine for me:

#include <glib.h>

typedef struct {
    char name[10];
} A;

A global_A = { "name here" };

A *
get_instance_of_A(void)
{
    return &global_A;
}

int
main(int argc, char **argv)
{
    const A *inst = get_instance_of_A();
    char *str = g_strdup(inst->name);
    g_print("%s\n", str);
    return 0;
}


use gchar instead of char in struct.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号