How to provide Sentinel value at the end of Structure Array

a 夏天 提交于 2019-12-12 13:22:43

问题


I've created a structure of 10 elements (11th for sentinel value) and a structure pointer, assigning address of first structure element to it.

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++;
}  

How do I provide a sentinel value in the end of a structure array ?

EDIT : values in structure are changing dynamically i.e. i've created space for 10 structures but it might happen their will be only 5 elements present their at a moment. and sentinel value at 6th position.
when user enters a new structure element, sentinel value shifts forward etc so i can not use a (int i < 10) condition to simply print all the values.


回答1:


Your sentinel must be of type int (or some other field within struct student), such as:

s[10].roll_no = -1;

Your while loop will be as follows:

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


来源:https://stackoverflow.com/questions/24720551/how-to-provide-sentinel-value-at-the-end-of-structure-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!