I'm having an Algorithms course next semester and so I dived into C with the purpose of making a few data structures ahead of time to be prepared.
As I learned about function pointers, I found I could store them in structs and create an object-oriented-like use for my data structure. Here's an example:
#include <stdio.h>
void insert(char * object)
{
printf("Adding %s to the data structure\n", object);
}
typedef struct data_structure {
char * obj;
void (*insert)(char * object);
} data_structure;
int main()
{
data_structure d;
d.insert = insert;
d.insert("bacon");
return 0;
}
But is this kind of procedure actually useful in the scope of data structure and algorithm studying in C? Or is it just taking up memory on the data structure?
I've found other posts talking about function pointers, but none that explores this kind of approach. I think this could be useful to a bunch of curious students out there :)
In the past I have certainly seen objects constructed this way as sets of function pointers effectively representing a vtable. Usually, for a vtable you add one extra level of indirection such that all data objects with similar traits point to the same function pointer object. This reduces the cost per data object if there is more than 1 function, but at a slight execution cost.
It can also be used as a lightweight way to organise and structure function+voiddata callback objects, by insisting that the first member of the data is the callback function. Of course, you can't define inherited classes using c, but you can have nested structures which can be bullied to the same purpose.
After reading all the answers, here's the insight this post gathered regarding the use of function pointers as C structure attributes.
Advantages:
Good ol' practise on a somewhat advanced subject if you're a student
Provides encapsulation and object oriented code in C
Gives you better understanding of the object orientated programming paradigm if you're not already well familiarized with it
Can be used to implement VTables
Disadvantages:
On a functional level, you still have to pass the data structure to the function, as it doesn't have access to said data structure
Slight performance overhead
In conclusion, the use of function pointers as in the original question would really only have practical uses if one wishes to explore OOP whilst getting into more advanced aspects of C, or to construct VTables.
Thank you to all the people who replied.
How would you do a functionally pure linked list in C? Is a linked list what I should even be doing? I'm trying to have a list of objects but I can't think of how to add an item to the list from a function without modifying outside states.
I basically want this:
void AddItemToList(Item item);
To be able to be called from anywhere, without the caller having to worry about what list is being added to.
Right now I just have:
void AddTypeToList(entityType_t *type, entityType_t *listHead)
{
type->next = listHead;
listHead = type;
}
void RegisterEntityType(entityType_t *type)
{
AddTypeToList(type, typeList);
}
But this is obviously not functional (or is it?) because RegisterEntityType is modifying typeList. (which is a global entityType_t)
You'd need a different function, generically speaking,
List AddItemToList(List list, Item item);
Because you should return a new list with the item added, without modifying the original list. This involves other questions, such as that a Garbage Collector should be needed in order to keep track of the intermediate lists your are going to create and discard.
I don't think that C is the best language to implement functional programming techniques, you'll have to build everything from the ground up. The obvious, ideal choice would be a pure functional programming language, or at least a programming language with support for functional techniques, such as for example C++, C# or Python.
Maybe you would like to check this question.
Hope this (somehow) helps.
I need to do a home assignment in VC++, which uses ADT to do several operations on an integer list. For now, we're not allowed to use classes, so I need to use struct.
I don't quite understand how ADTs work, so I'm not sure where to start, because all tutorials on the internet use classes, which I don't want to.
So are there any tutorials on the net that: 1. explain the concept of Abstract Data Types and 2. Provide an example of implementation (preferably in C++ and not using class, but struct instead).
I will give a try for an answer that is more what is my understanding.
What is an abstract datatype?
Always my first shot: Look at http://en.wikipedia.org/wiki/Abstract_data_type
My "practical" understanding of this is: There is some idea of an object that is defined by the object, its variables (or data) and the operations that are defined on this object.
For your case the object is a list of integers. The operations are something like insert a new integer, remove an integer, get the number of integers stored in the list and so on. When implementing this datatype you have to write this operations as functions. To provide this functions you will have to make up some structure to save the data to operate on.
Provide an example of implementation.
Well I won't do your homework so I will do some pseudocode:
struct ListElement {
int value;
type NextElement; //i leave the type to you
};
void insertBehind(ListElement &element, int newValue)//this is one way to do this
{
ListElement newElement(newValue); //create the new element (use new instead, don't want to "spoiler" the type to you)
newElement.nextElement = element.nextElement; //set the next element of this new one
element.NextElement = newElement; //set the new element
}
...
Hello I have started writing common data structure library in C similar to STL.
Here is the link . http://code.google.com/p/cstl/
I struggled a lot of whether to go ahead with having void* as basic element for data structure. and End up with structure which has two elements
typedef struct __c_lib__object {
void* raw_data;
size_t size;
} clib_object, *clib_object_ptr;
This approach allow me to store each element, but it requires lot of memory allocation , during saving and returning back the element from the container.
Can anybody please review this , and let me know if there is any other approach.
Thanks
Avinash
Names starting with double-underscore are reserved to 'the implementation' and should be avoided in user code.
Personally, I dislike typedefs for pointers; I'd rather use clib_object *x; than clib_object_ptr x;.
Why do you need to record the size of the object?
I'd like a C library that can serialize my data structures to disk, and then load them again later. It should accept arbitrarily nested structures, possibly with circular references.
I presume that this tool would need a configuration file describing my data structures. The library is allowed to use code generation, although I'm fairly sure it's possible to do this without it.
Note I'm not interested in data portability. I'd like to use it as a cache, so I can rely on the environment not changing.
Thanks.
Results
Someone suggested Tpl which is an awesome library, but I believe that it does not do arbitrary object graphs, such as a tree of Nodes that each contain two other Nodes.
Another candidate is Eet, which is a project of the Enlightenment window manager. Looks interesting but, again, seems not to have the ability to serialize nested structures.
Check out tpl. From the overview:
Tpl is a library for serializing C
data. The data is stored in its
natural binary form. The API is small
and tries to stay "out of the way".
Compared to using XML, tpl is faster
and easier to use in C programs. Tpl
can serialize many C data types,
including structures.
I know you're asking for a library. If you can't find one (::boggle::, you'd think this was a solved problem!), here is an outline for a solution:
You should be able to write a code generator[1] to serialize trees/graphs without (run-time) pre-processing fairly simply.
You'll need to parse the node structure (typedef handling?), and write the included data values in a straight ahead fashion, but treat the pointers with some care.
For pointer to other objects (i.e. char *name;) which you know are singly referenced, you can serialize the target data directly.
For objects that might be multiply refernced and for other nodes of your tree you'll have to represent the pointer structure. Each object gets assigned a serialization number, which is what is written out in-place of the pointer. Maintain a translation structure between current memory position and serialization number. On encountering a pointer, see if it is already assigned a number, if not, give it one and queue that object up for serialization.
Reading back also requires a node-#/memory-location translation step, and might be easier to do in two passes: regenerate the nodes with the node numbers in the pointer slots (bad pointer, be warned) to find out where each node gets put, then walk the structure again fixing the pointers.
I don't know anything about tpl, but you might be able to piggy-back on it.
The on-disk/network format should probably be framed with some type information. You'll need a name-mangling scheme.
[1] ROOT uses this mechanism to provide very flexible serialization support in C++.
Late addition: It occurs to me that this is not always as easy as I implied above. Consider the following (contrived and badly designed) declaration:
enum {
mask_none = 0x00,
mask_something = 0x01,
mask_another = 0x02,
/* ... */
mask_all = 0xff
};
typedef struct mask_map {
int mask_val;
char *mask_name;
} mask_map_t;
mask_map_t mask_list[] = {
{mask_something, "mask_something"},
{mask_another, "mask_another"},
/* ... */
};
struct saved_setup {
char* name;
/* various configuration data */
char* mask_name;
/* ... */
};
and assume that we initalize out struct saved_setup items so that mask_name points at mask_list[foo].mask_name.
When we go to serialize the data, what do we do with struct saved_setup.mask_name?
You will need to take care in designing your data structures and/or bring some case-specific intelligence to the serialization process.
This is my solution. It uses my own implementation of malloc, free and mmap, munmap system calls. Follow the given example codes. Ref: http://amscata.blogspot.com/2013/02/serialize-your-memory.html
In my approach I create a char array as my own RAM space. Then there are functions for allocate the memory and free them. After creating the data structure, by using mmap, I write the char array to a file.
Whenever you want to load it back to the memory there is a function which used munmap to put the data structure again to the char array. Since it has virtual addresses for your pointers, you can re use your data structure. That means, you can create data structure, save it, load it, again edit it, and save it again.
You can take a look on eet. A library of the enlightenment project to store C data types (including nested structures). Although nearly all libs of the enlightenment project are in pre-alpha state, eet is already released. I'm not sure, however, if it can handle circular references. Probably not.
http://s11n.net/c11n/
HTH
you should checkout gwlib. the serializer/deserializer is extensive. and there are extensive tests available to look at. http://gwlib.com/
I'm assuming you are talking about storing a graph structure, if not then disregard...
If your storing a graph, I personally think the best idea would be implementing a function that converts your graph into an adjacency matrix. You can then make a function that converts an adjacency matrix to your graph data structure.
This has three benefits (that may or may not matter in your application):
adjacency matrix are a very natural way to create and store a graph
You can create an adjacency matrix and import them into your applications
You can store and read your data in a meaningful way.
I used this method during a CS project and is definitely how I would do it again.
You can read more about adjacency matrix here: http://en.wikipedia.org/wiki/Modified_adjacency_matrix
Another option is Avro C, an implementation of Apache Avro in C.
Here is an example using the Binn library (my creation):
binn *obj;
// create a new object
obj = binn_object();
// add values to it
binn_object_set_int32(obj, "id", 123);
binn_object_set_str(obj, "name", "Samsung Galaxy Charger");
binn_object_set_double(obj, "price", 12.50);
binn_object_set_blob(obj, "picture", picptr, piclen);
// send over the network
send(sock, binn_ptr(obj), binn_size(obj));
// release the buffer
binn_free(obj);
If you don't want to use strings as keys you can use a binn_map which uses integers as keys.
There is also support for lists, and all these structures can be nested:
binn *list;
// create a new list
list = binn_list();
// add values to it
binn_list_add_int32(list, 123);
binn_list_add_double(list, 2.50);
// add the list to the object
binn_object_set_list(obj, "items", list);
// or add the object to the list
binn_list_add_object(list, obj);
In theory YAML should do what you want http://code.google.com/p/yaml-cpp/
Please let me know if it works for you.