Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用指针处理结构的动态表_C++_Pointers_Dynamic_Struct - Fatal编程技术网

C++ 使用指针处理结构的动态表

C++ 使用指针处理结构的动态表,c++,pointers,dynamic,struct,C++,Pointers,Dynamic,Struct,我做了一个练习,用一个函数将数据写到结构的动态表中。这是我的密码: #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; }

我做了一个练习,用一个函数将数据写到结构的动态表中。这是我的密码:

#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;
}
#包括
#包括
使用名称空间std;
结构学生{char name[15],姓氏[20];int age;};
学生*createTab(int tsize)
{
学生*t=新学生[tsize];
返回t;
}
填空(学生*t,整数t大小)
{
for(int i=0;i t[i].name;
cout>t[i].姓;
cout>t[i].年龄;
}
}
int main()
{
学生*t=createTab(10);
填充(t,20);

cout标准对订阅的定义如下:

5.2.1/1(…)表达式E1[E2]与*((E1)+(E2))完全相同(根据定义)

这就是为什么使用指针
t
和索引
i
*(t+i)
t[i]
是一样的。在结构字段的上下文中,代码的问题是优先级问题:您可以编写
(*(t+i))。name
或更好的
(t+i)->name
,或者更清晰一些,就像您所做的那样:
t[i].name


注意:如果你分配了一个带有
new[…]
的表,你必须用
delete[]
来释放它。所以是的:没关系!

谢谢你的完整回答!