我有一个练习,使用函数将数据写入动态结构表。这是我的代码:
#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 - 当我将指向表的第一个元素的指针插入函数时,我怎么可能用索引对整个表进行操作?
最佳答案
标准定义下标如下:
5.2.1/1 (...) The expression E1[E2] is identical (by definition) to *((E1)+(E2))
这就是为什么,使用指针 t
和索引 i
,*(t+i)
和 t[i ]
是一样的。您的代码在结构字段上下文中的问题是优先级问题:您可以编写 (*(t+i)).name
或更好的 (t+i)-> name
,或者像您所做的那样更清晰:t[i].name
。
P.S.:如果您使用 new[...]
分配一个表,您必须使用 delete[]
释放它。所以是的:没关系!
关于c++ - 使用指针处理动态结构表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982357/