【问题标题】:Handle a dynamic table of structures with pointers使用指针处理结构的动态表
【发布时间】: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


    【解决方案1】:

    标准对下标的定义如下:

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

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

    P.S.:如果你用new[...] 分配一个表,你必须用delete[] 释放它。所以是的:没关系!

    【讨论】:

    • 感谢您的完整回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2020-05-06
    • 1970-01-01
    • 2012-07-16
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多