Skip to content

TheBrokenPipe/CListTemplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CListTemplate

This is a list template, it allows you to create and use lists in C.

Usage

To create a list, you have to first define the list type in the global space with:

import_list(<type-name>, <list-type-name>);

For example, import_list(int, intlist);.

Aftwerwards, you can treat <list-type-name> as a list type and do the normal list operations:

intlist mylist = new(intlist); // Create new intlist.
list_add(mylist, 3); // Add 3 to back of list.
list_add(mylist, 8); // Add 8 to back of list.
int first = list_remove(mylist, 0); // Remove 0's element.
list_add(mylist, first - list_get(mylist, 0)); // Add (first - mylist[0]) to back of list.
int num = list_size(mylist); // Get number of elements in the list.
list_set(mylist, 0, 128); // Set mylist[0] to 128.
list_insert(mylist, 0, 64); // Insert 64 at index 0 (add to front of list).
list_clear(mylist); // Remove all elements in the list.
list_free(mylist); // Free the list (removes all elements automatically).

You can define lists for all types - integers, strings, pointers and structures. Struct example:

#include <stdio.h>
#include "list.h"

typedef struct
{
	const char *name;
	const char *user;
	int duration;
} job_t;

import_list(job_t, joblist);

joblist create_joblist(void)
{
	joblist jobs = new(joblist);
	job_t tomjob = { "Do Homework", "tom", 100 };
	job_t amyjob = { "Watch TV", "amy", 200 };
	list_add(jobs, tomjob);
	list_add(jobs, ((job_t){ "Eat Dinner", "james", 25 }));
	list_add(jobs, amyjob);
	list_add(jobs, ((job_t){ "Sleep", "jan", 800 }));
	return jobs;
}

int main(int argc, char **argv)
{
	joblist jobs = create_joblist();
	printf("Total %zu jobs:\n", list_size(jobs));
	for (int i = 0; i < list_size(jobs); i++)
	{
		printf("%s %s %d\n", list_get(jobs, i).name, list_get(jobs, i).user, list_get(jobs, i).duration);
	}
	list_free(jobs);
	return 0;
}

Limitations

  • While lists can be defined in headers, doing so may result in those lists being defined multiple times (once by each C file). This will not cause syntax errors (as all functions generated by list.h are static), but can result in huge executables.

About

List template for C

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages