繁体   English   中英

如何将Struct的特定元素存储到指针中

[英]How to store specific elements of Struct into pointer

好的,所以我的指针逻辑有点缺陷,但我正在研究它。 我的问题是在下面的main.cpp文件中,在getStructData()函数内部。 我在评论中列出了问题,我认为似乎是正确的,但知道不是。 我现在在评论中提出这个问题。

我有一个函数getMyStructData(),我当前可以根据索引号打印出特定结构的元素。 相反,我想将给定索引号(int structureArrayIndex)的结构元素从私有结构复制到指针参数的结构中。

在myStructure.h中

struct myStructure
{
    int myInteger;
    double myDoublesArray[5];
    char myCharArray[80];

};

在myClass.h中

#include "myStructure.h"

class myClass
{
private:
    myStructure myStruct[5]

private:
    Prog1Class();
    ~Prog1Class();
    void setMyStructData();
    void getMyStructData(int structureArrayIndex, struct myStructure *info);
};

在main.cpp里面

#include<iostream>
#include <string>
#include "myClass.h"
#include "myStructure.h"

using namespace std;

void myClass::setMyStructData()
{
    for(int i = 0; i < 5 ; i++)
    {
        cout << "Please enter an integer: " << endl;
        cin >> myStruct[i].myInteger;

        for(int j = 0; j< 5; j++)
        {
            cout << "Please enter a double: ";
            cin >> myStruct[i].myDoublesArray[j];
        }

        cout << endl << "Please enter a string: ";
        cin.ignore(256, '\n');
        cin.getline(myStruct[i].myCharArray, 80, '\n');
    }
}

void Prog1Class::getStructData(int structureArrayIndex, struct myStructure *info)
{
//****Below I have what's working, but Instead of just printing out the elements, what I want to do is copy the elements of that struct at the given index number (int structureArrayIndex) from that private structure into the structure of the pointer argument.  

//I'm guessing something like this:
// info = &myStructure[structureArrayIndex];
//I know that's wrong, but that's where I'm stuck.  

//****Here is how I would print out all of the data using the int structureArrayIndex
cout << myStruct[structureArrayIndex].myInteger << endl;
for (int k = 0; k < 5; k++)
{
    cout << myStruct[structureArrayIndex].myDoublesArray[k] << endl;
}
cout << myStruct[structureArrayIndex].myCharArray << endl;

}

int main(void)
{
    myClass c;
    c.setMyStructData();
    c.getStructData(1);

    cin.get();
}

在注释的代码中,您要分配指针而不是数据的实际副本。

要使用您提供的代码执行您所要求的操作,您可以:

  // Check that info isn't null
  if (!info) {
    return;
  }
  // Simple copy assignment of private structure to info.
  *info = myStruct[structureArrayIndex];

这将取消引用指针信息,并在structureArrayIndex的myStruct数组中执行myStructure类型的默认复制操作。

您必须将myStruct[structureArrayIndex]的内容分配给info内容。

*info = myStruct[structureArrayIndex];

暂无
暂无

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

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