简体   繁体   English

关于 C 中的结构,如何将数据从结构复制到字符串数组

[英]Regarding structs in C, how to copy the data from a struct to a string array

I have a program if finds servers on the network using mDNS.如果使用 mDNS 在网络上找到服务器,我有一个程序。 It is from a opensource stack.它来自开源堆栈。 Currently, I am in need of guidance for the following use case.目前,我需要以下用例的指导。 USECASE: Whenever I run the program to findServers, I plan to add an additional logic, which tries to connect to the servers mentioned, and if the connection has failed, I print a warning message saying the network connection on the server could be faulty.用例:每当我运行程序查找服务器时,我计划添加一个额外的逻辑,它尝试连接到提到的服务器,如果连接失败,我会打印一条警告消息,说明服务器上的网络连接可能有故障。

So to the code,所以对于代码,

it has a struct of type as defined below它具有如下定义的类型结构

typedef struct {
    size_t length; /* The length of the string */
    UA_Byte *data; /* The content (not null-terminated) */
} UA_String;

typedef struct {
    UA_UInt32 recordId;
    UA_String serverName;
    UA_String discoveryUrl;
    size_t serverCapabilitiesSize;
    UA_String *serverCapabilities;
} UA_ServerOnNetwork;

The default code has the logic which runs this way:默认代码具有以这种方式运行的逻辑:

for(size_t i = 0; i < serverOnNetworkSize; i++) {
            UA_ServerOnNetwork *server = &serverOnNetwork[i];
            printf("Server[%lu]: %.*s", (unsigned long) i,
                   (int) server->serverName.length, server->serverName.data);
            printf("\n\tRecordID: %d", server->recordId);
            printf("\n\tDiscovery URL: %.*s", (int) server->discoveryUrl.length,
                   server->discoveryUrl.data);



            printf("\n\tCapabilities: ");
            /*for(size_t j = 0; j < server->serverCapabilitiesSize; j++) {
                printf("%.*s,", (int) server->serverCapabilities[j].length,
                       server->serverCapabilities[j].data);
            }*/

            //added below
            printf("%.*s", (int) server->serverCapabilities[0].length,
                                   server->serverCapabilities[0].data);
            printf("\n\tStatus: ");
            printf("%.*s", (int) server->serverCapabilities[1].length,
                                               server->serverCapabilities[1].data);


            printf("\n\n");
        }

And the output observed is of the form观察到的 output 的形式为

Server[0]: name1
    RecordID: 0
    Discovery URL: opc.tcp://hostname2:4840
    Capabilities: LDSME-DESKTOPSIDE
    Status: Available

Server[1]: name2
    RecordID: 1
    Discovery URL: opc.tcp://hostname:4842
    Capabilities: Crane
    Status: Starting...

Server[2]: hostname
    RecordID: 2
    Discovery URL: opc.tcp://hostname:4840
    Capabilities: LDSME-NOTEBOOKSIDE
    Status: AVailable

This would be the default case.这将是默认情况。 But I plan to ping each of the URL's mentioned( or try to send a message) to check if the network is all fine.但我计划对提到的每个 URL 进行 ping 操作(或尝试发送消息)以检查网络是否一切正常。 So I plan to extract the URL information.所以我打算提取URL信息。

Hence I declared a character array A, and tried copied the contents from the server->discoveryURL.data to the array A, using strcpy and memcpy function.因此,我声明了一个字符数组 A,并尝试使用 strcpy 和 memcpy function 将内容从 server->discoveryURL.data 复制到数组 A。

But it fails.但它失败了。

for(size_t i = 0; i < serverOnNetworkSize; i++) {
           UA_ServerOnNetwork *server = &serverOnNetwork[i];
           strcpy(A[i], server->discoveryUrl.data);
           printf("URL %d: %s\n",(unsigned long) i,A[i]);

        }

It fails and does not even run through the loop.它失败了,甚至没有通过循环。 Need some guidance to have an output of the below format需要一些指导才能获得以下格式的 output

URL 0 : opc.tcp://hostname2:4840
URL 1 : opc.tcp://hostname:4842
URL 2 : opc.tcp://hostname:4840

Also I do not understand why, in the printf statement of a struct string "%s" gives an additional character at the end, while "%.*s" gives the correct output.我也不明白为什么,在结构字符串“%s”的 printf 语句中,最后给出了一个附加字符,而“%.*s”给出了正确的 output。 Please looking forward for guidance.请期待指导。

EDIT: I have modified the code a bit and have introduced a new global character Array, and have used memcpy functions.编辑:我稍微修改了代码并引入了一个新的全局字符数组,并使用了 memcpy 函数。 But I am struggling as I am getting an extra character in the URL field.但是我很挣扎,因为我在 URL 字段中获得了一个额外的字符。

char *A[] = {};
int main(){

for(size_t i = 0; i < serverOnNetworkSize; i++) {
           UA_ServerOnNetwork *server = &serverOnNetwork[i];        
           A[i] = (char*)UA_malloc(server->discoveryUrl.length+1); 
       memcpy(A[i],server->discoveryUrl.data,server->discoveryUrl.length);  
           printf("URL %d: %.*s\n",(unsigned long) i,A[i]);
        }
}

The output is seen as: output 被视为:

URL 0: opc.tcp://o755-gksr:48401
URL 1: opc.tcp://o755-gksr:48421

There is an extra character 1 at the end which is wrong.最后有一个额外的字符 1 是错误的。 Any guidance on how to handle that please.请提供有关如何处理的任何指导。

You need to terminate the string data with a '\0' after copying it.您需要在复制后使用 '\0' 终止字符串数据。 That way printf's %s will know when to stop:这样 printf 的 %s 将知道何时停止:

// first we need some memory for the destination of the copy
A[i] = malloc(server->discoveryUrl.length+1); // +1 for the '\0' at the end
// then we copy exactly the number of characters we want
strncpy(A[i], server->discoveryUrl.data, server->discoveryUrl.length);
// then we add the '\0' terminator
A[i][server->discoveryUrl.length] = '\0'; // add the '\0' at the end

Here's a sample:这是一个示例:

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

// defien these so we don't need mDNS
typedef char UA_Byte;
typedef uint32_t UA_UInt32;

typedef struct {
    size_t length; /* The length of the string */
    UA_Byte *data; /* The content (not null-terminated) */
} UA_String;

typedef struct {
    UA_UInt32 recordId;
    UA_String serverName;
    UA_String discoveryUrl;
    size_t serverCapabilitiesSize;
    UA_String *serverCapabilities;
} UA_ServerOnNetwork;

// for testing we only need one of these
UA_ServerOnNetwork serverOnNetwork[1] = {
    {
        1,          // recordId
        {3,"abcd"}, // serverName
        {3,"efgh"}, // discoveryUrl
        0,          // serverCapabilitiesSize
        NULL        // serverCapabilities
    }
};
int serverOnNetworkSize = sizeof(serverOnNetwork)/sizeof(serverOnNetwork[0]);

int main() {

    // first print it using the %.*s printf formatter
    for(size_t i = 0; i < serverOnNetworkSize; i++) {
        UA_ServerOnNetwork *server = &serverOnNetwork[i];
        printf("Server[%lu]: %.*s", (unsigned long) i,
                (int) server->serverName.length, server->serverName.data);
        printf("\n\tRecordID: %d", server->recordId);
        printf("\n\tDiscovery URL: %.*s", (int) server->discoveryUrl.length,
                server->discoveryUrl.data);
    }

    // now make an array of '\0' terminated strings, fill them in, and print them
    printf("\n\nURLs:");
    char *A[serverOnNetworkSize];
    for(size_t i = 0; i < serverOnNetworkSize; i++) {
        UA_ServerOnNetwork *server = &serverOnNetwork[i];
        // first we need some memory for the destination of the copy
        A[i] = malloc(server->discoveryUrl.length+1); // +1 for the '\0' at the end
        // then we copy exactly the number of characters we want
        strncpy(A[i], server->discoveryUrl.data, server->discoveryUrl.length);
        // then we add the '\0' terminator
        A[i][server->discoveryUrl.length] = '\0'; // add the '\0' at the end
        // and finally we print it
        printf("\n\tURL %lu: %s\n", (unsigned long) i, A[i]);
    }

    return 0;
}

Try it here: https://godbolt.org/z/cbcsdG在这里试试: https://godbolt.org/z/cbcsdG

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

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