Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a struct in C?

Tags:

c

struct

This is code for a linked list in the C programming language.

#include <stdio.h>    /* For printf */
#include <stdlib.h>   /* For malloc */

typedef struct node {
    int data;
    struct node *next; /* Pointer to next element in list */
} LLIST;

LLIST *list_add(LLIST **p, int i);
void list_remove(LLIST **p);
LLIST **list_search(LLIST **n, int i);
void list_print(LLIST *n);

The code is not completed, but I think it's enough for my question. Here at the end of struct node "LLIST" is used, and it's also used as a return type in the prototyping of the function list_add. What is going on?

like image 541
Pranjut Avatar asked Aug 06 '09 08:08

Pranjut


People also ask

Why would you use a struct?

Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. 5) A struct is a value type. If you assign a struct to a new variable, the new variable will contain a copy of the original.

Can a struct have a function in C?

1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

How do you initialize a structure in C?

Structure Initialization Just after structure declaration put the braces (i.e. {}) and inside it an equal sign (=) followed by the values must be in the order of members specified also each value must be separated by commas. The example below will show how to initialize structure variable in C programming.


2 Answers

That's a typedef. It's actually doing two things at once. First, it defines a structure:

struct node {
    int data;
    struct node *next;
}

And then does a typedef:

typedef struct node LLIST;

That means LLIST is a type, just like int or FILE or char, that is a shorthand for struct node, your linked-list node structure. It's not necessary - you could replace LLIST with struct node in all of those spots - but it makes it a bit easier to read, and helps hide the implementation from pesky end-users.

like image 52
Chris Lutz Avatar answered Sep 22 '22 15:09

Chris Lutz


LLIST is just another type name for the struct that has been created. In general, the following format will create a type "NAME" that is a "struct x":

typedef struct x { ... } NAME;
like image 20
Amber Avatar answered Sep 19 '22 15:09

Amber