【问题标题】:How to provide Sentinel value at the end of Structure Array如何在结构数组的末尾提供 Sentinel 值
【发布时间】:2014-09-03 10:13:38
【问题描述】:

我创建了一个包含 10 个元素的结构(第 11 个用于标记值)和一个结构指针,将第一个结构元素的地址分配给它。

struct student
{
    int roll_no;
};

struct student s[11];  
struct student *ptr = &s[0];    

s[10] = NULL;    // Sentinel value
while (*ptr != NULL )  // Sentinel Controlled Loop
{
    printf ("%d - ", ptr -> roll_no);

    ptr++;
}  

如何在结构数组的末尾提供一个标记值?

编辑:结构中的值是动态变化的,即我已经为 10 个结构创建了空间,但可能会发生它们一次只有 5 个元素出现。和第 6 位的哨兵值。
当用户输入一个新的结构元素时,哨兵值向前移动等 所以我不能使用 (int i

【问题讨论】:

    标签: c structure sentinel


    【解决方案1】:

    您的标记必须是int 类型(或struct student 中的某个其他字段),例如:

    s[10].roll_no = -1;
    

    您的while 循环如下:

    while(ptr->roll_no != -1)
    {
        ...
        ptr++;
    }
    

    【讨论】:

    • 感谢您的解决方案。虽然只是出于好奇,但在不占用额外结构空间的情况下,它们是否可以成为任何其他有效的方法?
    • @BrainDead 单链表会是更好的解决方案。
    猜你喜欢
    • 2014-12-30
    • 2012-03-27
    • 1970-01-01
    • 2016-09-06
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多