[英]How to access elements from an array of structure
我有:
struct strType{
char *str1;
char buff[128];
};
struct strType sType[3] = {
"String1", "",
"String2", "",
"string3" ""
};
如何將字符串分配給 buff? 我的要求是我需要兩個並行字符串,一個是預定義的,另一個是在運行時決定的。 我正在考慮使用結構數組。 但無法使用它們。
使用sType[index].buff
訪問數組中struct strType
實例的buff
部分。 可以使用標准strcpy
復制字符串:
strcpy(sType[0].buff, "String to put in buffer");
但是,在將數據復制到像這樣的固定大小的緩沖區中時,使用strncpy
會更安全(因為否則你會打開緩沖區溢出的可能性,並且有人會崩潰或控制你的進程):
strncpy(sType[0].buff, "String to put in buffer", sizeof(sType[0].buff));
我假設您正在尋找首先初始化一個結構數組。 在這種情況下,您的代碼應如下所示:
struct strType{
char *str1;
char buff[128];
};
struct strType sType[3] = {
{ NULL, "String1" },
{ NULL, "String2" },
{ NULL, "string3" }
};
然后,您可以使用喬恩的答案中的strncpy將字符串復制到strType.buff
。 請注意,您必須先將 memory 分配給strType.str
,然后才能將字符串復制到其中。
您需要像這樣初始化結構:
struct strType sType[3] = { {"String1", " "},{"String2", ""},{"string3", " "} };
然后你可以像 Jon 提到的那樣使用 strcpy,一旦你有了你的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.