【发布时间】:2016-01-24 22:33:14
【问题描述】:
我有一个使用函数将数据写入动态结构表的练习。这是我的代码:
#include <iostream>
#include <cstdlib>
using namespace std;
struct student{ char name[15], surname[20]; int age; };
student * createTab(int tsize)
{
student *t = new student[tsize];
return t;
}
void fill(student *t, int tsize)
{
for (int i = 0; i<2; i++)
{
cout << "Enter a name: "; cin >> t[i].name;
cout << "Enter a surname: "; cin >> t[i].surname;
cout << "Enter age: "; cin >> t[i].age;
}
}
int main()
{
student *t = createTab(10);
fill(t, 20);
cout << t[0].surname << endl;
cout << t[1].name << endl;
system("pause");
delete[]t;
return 0;
}
它工作,好的。但是在这里,在fill() 函数中,我使用student[].name 的索引语法。我总是在带有类似指针的表上工作:*(table+i) 在 for 循环中。 *(t+i).name 不起作用。我可以使用指针迭代结构字段吗?
P.S - 我是否正确释放内存?
我猜 P.S 2 - 当我将指向表的第一个元素的指针插入到函数中时,这怎么可能,然后我可以使用索引对整个表进行操作?
【问题讨论】:
标签: c++ pointers dynamic struct