Struct

Navigation:  Programming language SQC > Language elements > Variables >

Struct

Previous pageReturn to chapter overviewNext page

A struct is a group of data elements grouped under one name.

These data elements can have different types and different lengths.

Data structures can be declared in SQC using the following syntax:

 

struct struct_name

{

  type1 name1;

  type2 name2;

  type3 name3;

  ...

} object;

 

struct struct_name object_name;

 

 

Example:

 

 

typedef struct 

{

   struct node_t *left;

   struct node_t *right;

   int data;

   

}node_t;

 

node_t* get_new_node()

{

    node_t *nd = malloc(sizeof(node_t));

    

    if(nd == 0)

    {

      printf("Allocation failed \n");

      return -1;

    }

 

    return nd;

}

 

node_t* new_list()

{

   node_t *new_ = get_new_node();

   

   new_->data = -1;

   new_->right = new_;

   new_->left = new_;

   

   return new_;

}

 

node_t* insert_right(node_t *list, int data)

{

   node_t *new_ = get_new_node();

 

   new_->data = data;

   new_->left = list;

   new_->right = list->right;

   list->right = new_;

   new_->right->left = new_;

 

   return new_;

}

 

node_t* delete_(node_t* list)

{

   list->right->left = list->left;

   list->left->right = list->right;

 

   return list->left;

}

 

node_t* restore(node_t *list)

{

   list->right->left = list;

   list->left->right = list;

 

   return list;

}

 

void print_all(node_t* list)

{

   node_t *head = list;

   node_t *current = list;

   

   printf("%d ", head->data);

 

   current = current->right;

 

   while (head != current)

   {

      printf("%d ", current->data);

      current = current->right;

   }

}

 

int main(void)

{

    node_t 

     *head = new_list(),

     *current = head;

 

   for (int i = 1; i <= 10; i++ ) 

    {

      current = insert_right(current, i);

   }

 

    printf("\nList from head:\n");

   print_all(head);

   printf("\nList from current:\n");

   print_all(current);

 

   current = current->left;

   current = delete_(current);

   printf("\nList after delete:\n");

   print_all(head);

 

   current = delete_(head);

   printf("\nList after head delete:\n");

   print_all(current);

 

   head = restore(head);

   printf("\nList after head restore:\n");

   print_all(head);

   

   return 0;

 

}

 

Output:

 

List from head:

-1 1 2 3 4 5 6 7 8 9 10 

List from current:

10 -1 1 2 3 4 5 6 7 8 9 

List after delete:

-1 1 2 3 4 5 6 7 8 10 

List after head delete:

10 1 2 3 4 5 6 7 8 

List after head restore:

-1 1 2 3 4 5 6 7 8 10