简体   繁体   English

C 编程 - 将 struct 成员变量分配给 char *

[英]C programming - assign a struct member variable to a char *

I have a variable declared as const char * server = NULL;我有一个变量声明为const char * server = NULL;

This variable is assigned a value when the user passes the IP address of a server as a command line argument to the C program using the code below.当用户使用以下代码将服务器的 IP 地址作为命令行参数传递给 C 程序时,会为该变量分配一个值。 For example, running ./cprogram -h 10.4.0.01例如,运行./cprogram -h 10.4.0.01

opt = 1;
while (opt < argc)
{
    if (argv[opt] == NULL    ||
        argv[opt][0] != '-'  ||
        argv[opt][2] != 0)
    {
        print_usage();
        return 0;
    }

    switch (argv[opt][1])
    {
        case 'h':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            server = argv[opt];
            break;
    }

I am removing the need to pass command line arguments from the program and putting the values in an .ini file.我不需要从程序中传递命令行参数并将值放在 .ini 文件中。

I now read an .ini file at the start of the program and store the values in a struct.我现在在程序开始时读取 .ini 文件并将值存储在结构中。

struct lwm2m_object {
    char clientname[LG_BUF];
    char ipv4[LG_BUF];
    char server[LG_BUF];
};

In the correct way to assign the struct member variable server to the variable const char * server using this以正确的方式将结构成员变量server分配给变量const char * server使用此

server = &(lwm2m.server);

The assignment is not correct.分配不正确。 The correct assignment is正确的赋值是

server = lwm2m.server;

Your您的

server = &(lwm2m.server);

is doubly wrong .双重错误 First, the string you intend to copy is lwm2m.server -- remember that an array decays to a pointer.首先,您要复制的字符串是lwm2m.server —— 请记住,数组衰减为指针。 So, better is所以,更好的是

server = lwm2m.server;    // Still dangerous

But this merely copies the pointer to the data ( shallow copy ).但这只是复制指向数据的指针(浅拷贝)。 If the lwm2m_object lwm2m goes out of scope, then the associated string lwm2m_object::server is freed and may be re-used.如果lwm2m_object lwm2m超出范围,则关联的字符串lwm2m_object::server被释放并可重新使用。 In other words, your copy in server then becomes a dangling pointer .换句话说,你在server的副本然后变成了一个dangling pointer

If you know that lwm2m survives server (so that there is no danger of getting a dangling pointer), then the shallow copy is okay (and preferable).如果您知道lwm2m server存活(这样就没有获得悬空指针的危险),那么浅拷贝就可以了(并且更可取)。 Otherwise, you must make a deep copy, using strcpyn :否则,您必须使用strcpyn进行深度复制:

const char server[LG_BUF];
strcpyn(server, lwm2m.server, LG_BUF);

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

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