简体   繁体   English

如何访问结构数组中的元素

[英]How to access elements from an array of structure

I have:我有:

struct strType{
     char *str1;
     char buff[128];  
    };

struct strType sType[3] = {
                            "String1", "",
                            "String2", "",
                            "string3" ""  
                           };

How can I assign a string to buff?如何将字符串分配给 buff? My requirement is that I need two parallel strings one which is predefined and other which is decided on run time.我的要求是我需要两个并行字符串,一个是预定义的,另一个是在运行时决定的。 I am thinking of using array of structures.我正在考虑使用结构数组。 But not able to use them.但无法使用它们。

Accessing the buff part of an instance of struct strType inside the array is done with sType[index].buff .使用sType[index].buff访问数组中struct strType实例的buff部分。 Copying the string can be done with standard strcpy :可以使用标准strcpy复制字符串:

strcpy(sType[0].buff, "String to put in buffer");

However , it's much safer to use strncpy when copying data into fixed-size buffers like this (because otherwise you open up possibilities for buffer overruns and someone crashing or taking control of your process):但是,在将数据复制到像这样的固定大小的缓冲区中时,使用strncpy会更安全(因为否则你会打开缓冲区溢出的可能性,并且有人会崩溃或控制你的进程):

strncpy(sType[0].buff, "String to put in buffer", sizeof(sType[0].buff));

I am assuming you are looking for firstly initializing an array of structs.我假设您正在寻找首先初始化一个结构数组。 In that case your code should look like this:在这种情况下,您的代码应如下所示:

struct strType{
     char *str1;
     char buff[128];  
    };

struct strType sType[3] = {
                            { NULL, "String1" },
                            { NULL, "String2" },
                            { NULL, "string3" } 
                          };

You can then use strncpy as in Jon's answer to copy a string to strType.buff .然后,您可以使用乔恩的答案中的strncpy将字符串复制到strType.buff Note that you will have to allocate memory to strType.str before you can copy a string to it.请注意,您必须先将 memory 分配给strType.str ,然后才能将字符串复制到其中。

You need to initialize the struct like this:您需要像这样初始化结构:

struct strType sType[3] = { {"String1", " "},{"String2", ""},{"string3", " "} };

And then you can use strcpy as Jon mentioned once you have your string with you然后你可以像 Jon 提到的那样使用 strcpy,一旦你有了你的字符串

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

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