Often stacks in C are dependent upon datatype used to declare them. For example,
int arr[5]; //creates an integer array of size 5 for stack use
char arr[5]; //creates a character array of size 5 for stack use
are both limited to holding integer and character datatypes respectively and presumes that the programmer knows what data is generated during the runtime. What if I want a stack which can hold any datatype?
I initially thought of implementing it as a union, but the approach is not only difficult but also flawed. Any other suggestions?
I would use a structure like this:
struct THolder
{
int dataType; // this is a value representing the type
void *val; // this is the value
};
Then use an array of THolder to store your values.
This is really just a variant of Pablo Santa Cruz' answer, but I think it looks neater:
typedef enum { integer, real, other } type_t;
typedef struct {
type_t type;
union {
int normal_int; /* valid when type == integer */
double large_float; /* valid when type == real */
void * other; /* valid when type == other */
} content;
} stack_data_t;
You still need to use some way to explicitly set the type of data stored in each element, there is no easy way around that.
You could look into preprocessor magic relying on the compiler-dependent typeof keyword to do that automagically, but that will probably not do anything but ruin the portability.
Some people have suggested a void* member. In addition to that solution I'd like to offer an alternative (assuming your stack is a linked list of heap-allocated structures):
struct stack_node
{
struct stack_node *next;
char data[];
};
The data[] is a C99 construct. data must be the last member; this takes advantage of the fact that we can stuff arbitrary quantities after the address of the struct. If you're using non-C99 compiler you might have to do some sketchy trick like declare it as data[0].
Then you can do something like this:
struct stack_node*
allocate_stack_node(size_t extra_size)
{
return malloc(sizeof(struct stack_node) + extra_size);
}
/* In some other function... */
struct stack_node *ptr = allocate_stack_node(sizeof(int));
int *p = (int*)ptr->data;
If this looks ugly and hacky, it is... But the advantage here is that you still get the generic goodness without introducing more indirection (thus slightly quicker access times for ptr->data than if it were void* pointing to a different location from the structure.)
Update: I'd also like to point out that the code sample I give may have problems if your machine happens to have different alignment requirements for int than char. This is meant as an illustrative example; YMMV.
You could use macros and a "container" type to reduce "type" from being per-element, to whole-container. (C99 code below)
#define GENERIC_STACK(name, type, typeid, elements) \
struct name##_stack { \
unsigned int TypeID; \
type Data[elements]; \
} name = { .TypeID = typeid }
Of course, your "TypeID" would have to allow every possible agreed-upon type you expect; might be a problem if you intend to use whole structs or other user-defined types.
I realize having a uniquely named struct type for every variable is odd and probably not useful... oops.
I created an library that works for any data type:
List new_list(int,int);
creates new list eg:
List list=new_list(TYPE_INT,sizeof(int));
//This will create an list of integers
Error append(List*,void*);
appends an element to the list. *Append accpts two pointers as an argument, if you want to store pointer to the list don't pass the pointer by pointer
eg:
//using the int list from above
int a=5;
Error err;
err=append(&list,&a)
//for an list of pointers
List listptr=new_list(TYPE_CUSTOM,sizeof(int*));
int num=7;
int *ptr=#
append(&listptr,ptr);
//for list of structs
struct Foo
{
int num;
float *ptr;
};
List list=new_list(TYPE_CUSTOM,sizeof(struct Foo));
struct Foo x;
x.num=9;
x.ptr=NULL;
append(&list,&x);
Error get(List*,int);
Gets data at index specified. When called list's current poiter will point to the data.
eg:
List list=new_list(TYPE_INT,sizeof(int));
int i;
for(i=1;i<=10;i++)
append(&list,&i);
//This will print the element at index 2
get(&list,2);
printf("%d",*(int*)list.current);
Error pop(List*,int);
Pops and element from the specified index
eg:
List list=new_list(TYPE_INT,sizeof(int));
int i;
for(i=1;i<=10;i++)
append(&list,&i);
//element in the index 2 will be deleted,
//the current pointer will point to a location that has a copy of the data
pop(&list,2);
printf("%d",*(int*)list.current);
//To use the list as stack, pop at index list.len-1
pop(&list,list.len-1);
//To use the list as queue, pop at index 0
pop(&list,0);
Error merge(List ,List);
Merges two list of same type. If types are different will return a error message in the Error object it returns;
eg:
//Merge two elements of type int
//List 2 will come after list 1
Error err;
err=merge(&list1,&list2);
Iterator get_iterator(List*);
Get an iterator to an list. when initialized will have a pointer to the first element of the list.
eg:
Iterator ite=get_iterator(&list);
Error next(Iterator*);
Get the next element of the list.
eg:
//How to iterate an list of integers
Iterator itr;
for(itr=get_iterator(&list); ite.content!=NULL; next(ite))
printf("%d",*(int*)ite.content);
https://github.com/malayh/C-List
Related
After passing a void* pointer as argument to a function, is there a way to specify the type to which it is cast as another parameter. If I have two structs like:
struct A{
int key;
char c;
}
struct B {
int key;
float d;
}
Is it possible to define a function,
void func(void * ptr, ...){
//operate on key
}
and pass a pointer to either structs to the function after casting to void* and access the key element from within the function.
Trying to understand the use of void*, how structure definitions are stored ( How are the offsets of various elements determined from the structure definition? ) and how ploymorphism may be implemented in c.
Was trying to see if I could write Binary Search tree functions that could deal with nodes of any struct.
After passing a void* pointer as argument to a function, is there a way to specify the type to which it is cast as another parameter.
Yes and no.
I suppose you're hoping for something specific to this purpose, such as a variable that conveys a type name that the function can somehow use to perform the cast. Something along the lines of a type parameter in a C++ template, or a Java generic method, for example. C does not have any such thing.
But of course, you can use an ordinary integer to convey a code representing which of several known-in-advance types to cast to. If you like, you can even use an enum to give those codes meaningful names. For example:
enum arg_type { STRUCT_A_TYPE, STRUCT_B_TYPE };
void func(void *ptr, enum arg_type type) {
int key = 0;
switch (type) {
case STRUCT_A_TYPE:
key = ((struct A *) ptr)->key;
break;
case STRUCT_B_TYPE:
key = ((struct B *) ptr)->key;
break;
default:
assert(0);
}
// ...
}
Note well that that approach allows accessing any member of the pointed-to structure, but if you only want to access the first member, and it has the same type in every structure type of interest, then you don't need to know the specific structure type. In that particular case, you can cast directly to the member type:
void func(void *ptr) {
int key = *(int *)ptr;
// ...
}
That relies on C's guarantee that a pointer to any structure, suitably cast, points to that structure's first member.
Trying to understand the use of void*, how structure definitions are store and how ploymorphism may be implemented in c.
That's awfully broad.
C does not offer polymorphism as a language feature, and C objects do not carry information about their type such as could be used to dispatch type-specific functions. You can, of course, implement that yourself, but it is non-trivial. Available approaches include, but are not limited to,
passing pointers to functions that do the right thing for the type of your data. The standard qsort() and bsearch() functions are the canonical examples of this approach.
putting some kind of descriptor object as the first member of every (structure) type. The type of that member can be a structure type itself, so it can convey arbitrarily complex data. Such as a vtable. As long as it is the first member of all your polymorphic structures, you can always access it from a pointer to one of them by casting to its type, as discussed above.
Using tagged unions of groups of polymorphic types (requiring that all the type alternatives in each group be known at build time). C then allows you to look at any members of the common initial sequence of all union members without knowing which member actually has a value. That initial sequence would ordinarily include the tag, so that you don't have to pass it separately, but it might include other information as well.
Polymorphism via (single-)inheritance can be implemented by giving each child type an object of its parent type as its first member. That then allows you to cast to (a pointer to) any supertype and get the right thing.
Lets say you had a sort function that takes a function as a parameter which implements the "compare" functionality of the sort. The sort would then be capable of sorting a list of any arbitrary struct, by handing it a comparer function that implements the correct order for your particular struct.
void bubbleSort(Node* start, bool comparerFunction(void* a, void* b))
Consider the following struct definition:
typedef struct {
int book_id;
char title[50];
char author[50];
char subject[100];
char ISBN[13];
} Book;
And this unremarkable linked list definition:
typedef struct node{
void* item;
struct node* next;
} Node;
Which can store an arbitrary struct in the item member.
Because you know the type of the members you've placed in your linked list, you can write a comparer function that will do the right thing:
bool sortByTitle(void* left, void* right) {
Book* a = (Book*)left;
Book* b = (Book*)right;
return strcmp(a->title, b->title) > 0;
}
And then call your sort like this:
bubbleSort(myList, sortByTitle);
For completeness, here is the bubbleSort implementation:
/* Bubble sort the given linked list */
void bubbleSort(Node *start, bool greaterThan(void* a, void* b))
{
int swapped, i;
Node* ptr1;
Node* lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (greaterThan(ptr1->item, ptr1->next->item))
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
/* function to swap data of two nodes a and b*/
void swap(Node *a, Node *b)
{
void* temp = a->item;
a->item = b->item;
b->item = temp;
}
I used to code in C++ and now I try to program in C.
Assume I have defined a struct
struct point{
int x;
int y;
}
Is there any data structure A in c that can support the following functionality:
Given two integers, say i and j, and two points, say p1 and p2.
A[i][j][p1][p2] can uniquely determine a value.
It sounds like a 4-d array. However, indexes are no longer a int, but user-defined struct.
You'll probably have to make your own structure. The C Programming Language by Kernighan and Ritchie has an example of making an associate map in c, and what I'll detail below is based on what I remember from that.
Basically you'll need a struct Map that contains struct Key and struct Value.
struct Map {
struct Key key;
struct Value value;
};
struct Key contains elements that determine the value (in your case 2 points and 2 ints)
struct Key {
struct point p1;
struct point p2;
int i;
int j;
};
struct Value is whatever you want your key to point to (you didn't say)
You now have a struct Map that associates your four inputs with a value, but a single map isn't that useful. You're going to want a whole array of them.
struct Map map[SIZE_OF_MAP];
If you don't want to linearly search the array for the Map struct you're looking for, you can make a hashing function that will bring you directly to it. Just define a function that takes the key and uses its value to assign it an index in the array. Use the hash to place the Map in the array and retrieve it from the array. (Note: I'm unsure if this is a correct example of hashing, please correct if this is completely wrong)
int get_hash(Key *key)
{
int result;
/* combine all inputs in some way */
result = key->i * key->i + (key->p1.x * key->p1.x) - (key->p2.x * key->p2.x)
/* make sure result isn't out of bounds of the array */
return (result % SIZE_OF_MAP);
}
If you use the hashing function you'll have to consider collisions (what happens when two keys give the same result for get_hash). When you use your array of Maps you'll need some form of collision resolution.
I'm wondering for a solution to the below problem. Please help.
Problem:
struct s{
int a;
int b;
}st;
I want a function to initialize the values at runtime. The problem is that I want to make it generic, so I want to pass the member name as input to the function and get it initialized.
fun_init(char* mem, int val)
{
// Find offset of the member variable in struct 'st'
// Assign the value
}
One straight solution is to use string comparision on the member name. But if I happen to add some extra variables at a later time, I'll have to modify the function, which I don't want.
Hope I was able to frame the ques clearly.
Thanks
C does not provide a way to find a symbol by name. See this thread for more information.
The simplest solution here is to use an associative array.
Read this thread if you need to mix value-types. (In your example, all value types are int, so you might not need this.)
void fun_init(int *storage, int val) {
*storage = val;
}
void something_else(void) {
struct s {
int a;
int b;
} st;
fun_init(&st.a, 42);
}
However, if you need to dynamically determine the key name, you are doing something wrong. If you need to store key/value pairs, perhaps you would be interested in the hashtable.
I'm guessing you want to initialize struct from either user input or persistency.
A solution involves creating an associative array as mentioned by #Domi.
The array is filled with key/value pairs such as (const char*, unsigned).
The key is the name of struct member and the value is the offset from the start of the struct.
Each struct will need to have a function that initializes the above array. You can get an offset to a member via the offsetof macro.
This will NOT work with structs that have bit fields (sub byte named members).
I'm really new to C programming and I'm still trying to understand the concept of using pointers and using typedef structs.
I have this code snippet below that I need to use in a program:
typedef struct
{
char* firstName;
char* lastName;
int id;
float mark;
}* pStudentRecord;
I'm not exactly sure what this does - to me it seems similar as using interfaces in Objective-C, but I don't think that's the case.
And then I have this line
pStudentRecord* g_ppRecords;
I basically need to add several pStudentRecord to g_ppRecords based on a number. I understand how to create and allocate memory for an object of type pStudentRecord, but I'm not sure how to actually add multiple objects to g_ppRecords.
defines a pointer to the struct described within the curly bracers, here is a simpler example
typedef struct {
int x;
int y;
}Point,* pPoint;
int main(void) {
Point point = {4,5};
pPoint point_ptr = &point;
printf("%d - %d\n",point.x,point_ptr->x);
pPoint second_point_ptr = malloc(sizeof(Point));
second_point_ptr->x = 5;
free(second_point_ptr);
}
The first declares an unnamed struct, and a type pStudentRecord that is a pointer to it. The second declares g_ppRecords to be a pointer to a pStudentRecord. In other words, a pointer to a pointer to a struct.
It's probably easier to think of the second as an "array of pointers". As such, g_ppRecords[0] may point to a pStudentRecord and g_ppRecords[1] to another one. (Which, in turn, point to a record struct.)
In order to add to it, you will need to know how it stores the pointers, that is, how one might tell how many pointers are stored in it. There either is a size somewhere, which for size N, means at least N * sizeof(pStudentRecord*) of memory is allocated, and g_ppRecords[0] through g_ppRecords[N-1] hold the N items. Or, it's NULL terminated, which for size N, means at least (N+1) * sizeof(pStudentRecord*) of memory is allocated and g_ppRecords[0] through g_ppRecords[N-1] hold the N items, and g_ppRecords[N] holds NULL, marking the end of the string.
After this, it should be straightforward to create or add to a g_ppRecords.
A struct is a compound data type, meaning that it's a variable which contains other variables. You're familiar with Objective C, so you might think of it as being a tiny bit like a 'data only' class; that is, a class with no methods. It's a way to store related information together that you can pass around as a single unit.
Typedef is a way for you to name your own data types as synonyms for the built-in types in C. It makes code more readable and allows the compiler to catch more errors (you're effectively teaching the compiler more about your program's intent.) The classic example is
typedef int BOOL;
(There's no built-in BOOL type in older ANSI C.)
This means you can now do things like:
BOOL state = 1;
and declare functions that take BOOL parameters, then have the compiler make sure you're passing BOOLs even though they're really just ints:
void flipSwitch(BOOL isOn); /* function declaration */
...
int value = 0;
BOOL boolValue = 1;
flipSwitch(value); /* Compiler will error here */
flipSwitch(boolValue); /* But this is OK */
So your typedef above is creating a synonym for a student record struct, so you can pass around student records without having to call them struct StudentRecord every time. It makes for cleaner and more readable code. Except that there's more to it here, in your example. What I've just described is:
typedef struct {
char * firstName;
char * lastName;
int id;
float mark;
} StudentRecord;
You can now do things like:
StudentRecord aStudent = { "Angus\n", "Young\n", 1, 4.0 };
or
void writeToParents(StudentRecord student) {
...
}
But you've got a * after the typedef. That's because you want to typedef a data type which holds a pointer to a StudentRecord, not typedef the StudentRecord itself. Eh? Read on...
You need this pointer to StudentRecord because if you want to pass StudentRecords around and be able to modify their member variables, you need to pass around pointers to them, not the variables themselves. typedefs are great for this because, again, the compiler can catch subtle errors. Above we made writeToParents which just reads the contents of the StudentRecord. Say we want to change their grade; we can't set up a function with a simple StudentRecord parameter because we can't change the members directly. So, we need a pointer:
void changeGrade(StudentRecord *student, float newGrade) {
student->mark = newGrade;
}
Easy to see that you might miss the *, so instead, typedef a pointer type for StudentRecord and the compiler will help:
typedef struct { /* as above */ } *PStudentRecord;
Now:
void changeGrade(PStudentRecord student, float newGrade) {
student->mark = newGrade;
}
It's more common to declare both at the same time:
typedef struct {
/* Members */
} StudentRecord, *PStudentRecord;
This gives you both the plain struct typedef and a pointer typedef too.
What's a pointer, then? A variable which holds the address in memory of another variable. Sounds simple; it is, on the face of it, but it gets very subtle and involved very quickly. Try this tutorial
This defines the name of a pointer to the structure but not a name for the structure itself.
Try changing to:
typedef struct
{
char* firstName;
char* lastName;
int id;
float mark;
} StudentRecord;
StudentRecord foo;
StudentRecord *pfoo = &foo;
I know that when defining a an enum you can enumerate through the list numerically:
typedef enum MONTH { Jan = 1, Feb, March, ... };
Can you enumerate through values in a struct the same way? I basically want to loop through the values in a struct using a for or while loop.
struct items {char *item_name, int item_value};
struct items Items_list[] =
{
"item 1", 2000,
"item 2", 3600,
....
};
Language used is C.
Edit: I may have just answered my own question since what I had in mind is an array of structs. Will leave the question up for now however.
This declaration and initializer combination are invalid. (The question changed while the original version of this answer was written.)
If you are asking "is there a way to access the first member of the structure, then the second, without knowing the structure element names", then the answer is 'no, not without careful encoding beforehand'.
The careful coding involves multiple steps. For each element, you need an encoding of the type, the offset of the member in the structure, and perhaps the size of the member (if the encoding of the type does not give that to you anyway):
typedef enum { MT_INT, MT_CHAR_PTR, ... } MemberType;
typedef struct MemberAccess
{
const char *name;
size_t offset;
MemberType type;
} MemberAccess;
static const MemberAccess members[] =
{
"item_name", offsetof(struct items, item_name), MT_CHAR_PTR },
"item_value", offsetof(struct items, item_value), MT_INT },
};
And now, with excruciating care, you can write code to either get or set the value in the Nth member of a struct item pointed at by a particular pointer. However, doing so is still far from trivial.
int get_int(const void *data, const MemberAccess *member)
{
assert(member->type == MT_INT);
return (*(const int *)((const char *)data + member->offset));
}
GCC notwithstanding, you need the cast to a character pointer; you cannot legitimately do pointer arithmetic on void *.
You might then invoke:
int value = get_int(&Items_list[1], &members[1]);
to get at the integer value of the second field of the second element of the array.
This is so excruciating to deal with that there have to be excellent reasons to go through the overhead. There can be such reasons. I know of a system with 400 configuration parameters (which is a problem in its own right, but lets pretend that's OK; they've accumulated over 20 years of development) stored in a structure with heterogeneous types for the members. The code that manipulates it is written out 400 times - ouch! - because it doesn't use a system driven off an analogue of the MemberAccess structure. The code would be a lot more compact than it currently is because there are about a dozen data types to deal with, so most of the code is repetitive. Another way of reducing the complexity of that code would be to make everything into a string, but there are issues with that transformation too.
No, you cannot iterate the elements of a struct. The best you can do is hardcode the names of the struct in the loop:
struct items *item = Items_list;
while (item < Items_list + sizeof(Items_list) / sizeof(*Items_list)) {
printf("%s %d", item->item_name, item->item_value);
++item;
}
Also note that you cannot reliably iterate an enum either, because it could be defined like this:
typedef enum MONTH { Jan = 1, Feb = 13, March = 10, ... };
And the elements are both out of order and non-continuous (i.e. there are gaps in the numbers).
One way to do this, when you have a pointer type in the inner struct, and when that pointer cannot be meaningfully NULL, is to do something like:
for (int i=0; Item_List[i].item_name != 0; i++) {
// do whatever
}
If you don't have a handy pointer type, a "sentinel" value can often be used to mark the last record.
You'll need to remember to add a null element/sentinel at the end of your structure array though, and fix your syntax.
No, there's no easy way to do this. A struct is not a numerical value, so you can't loop through its values/members. You can either use an array instead of a struct and access its memebers with a simple for loop, or write a special enumerator callback function which takes the struct as its one argument, a number as another argument, and using case or if statements, looks up each member of the structure.