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

标签 c++ class pointers struct

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

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

在 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 类型的默认复制操作。

关于c++ - 如何将 Struct 的特定元素存储到指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649638/

相关文章:

c++ - 我可以传递给函数的最大字符串长度(或大小)是多少?

c++ - 在 C++ 中,嵌套 vector 消耗大量内存

c++ - 坐标图像/离散空间中的几何操作

mysql - 如何从数据库图制作类图?

c - 将指针传递给 C 中的另一个函数

c++ - 你能改变指针指向的大小吗

c++: 无法解决 vector 订阅错误

一个元素上有两个类的 CSS 选择器

c# - 接口(interface)编译

c - 我可以从一个位置更改结构成员,但不能从另一个位置更改结构成员