简体   繁体   中英

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? 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 . Copying the string can be done with standard 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(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 . Note that you will have to allocate memory to strType.str before you can copy a string to it.

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

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