C program variable that holds cartesian coordinates? - c

I have never programmed in C and have not programmed in C++ for a little while and either way, I am still learning.
I am writing a program in C and am converting a MATLAB program to this C program. I have a lot of variables from MATLAB that are cartesian coordinates, X Y Z, of points. Is there a variable type I could use built into C? I need to subtract different points and also do other operations on them. Any suggestions?
Thanks,
DemiSheep
Edit:
Ok I have another question. I want to make sure this is a good idea. (But first, with stackoverflow is this how I should post more information to my post, by editing my original post? -Thanks!)
Question:
I have an object with several characteristics. Say it's a car and the car has several different parameters.
Parameters:
Position on map
Altitude (sea level?)
Start position
End Position
Can I use a struct or union (or both?) to have all these parameters inside the car "object" and update the parameters in the object like you would if it was it's own class in like C++ or Java?
Like if I want to calculate the distance the car traveled from the start position to its current position in like a Cartesian plane I could do something like:
distantTraveled = car.position - car.startPosition
Thanks,
DemiSheep

There are no built-in types that will do what you want.
You'll probably have to make your own small struct type such as the following.
typedef struct {
double x, y, z;
} coordinate;
If you're limited to C (rather than C++), you'll then need to build up a small library of functions to operate on these data types.
For what it's worth, I highly recommend looking around to find a library that will provide this type of thing for you. Ideally something specialized to the domain you're working in.

You would use a struct (typedef struct {double x,y,z;} point;) or an array (double p[3]).
If you want to get more clever you could use both by employing a union:
typedef union {
struct {double x,y,z;} s;
double a[3];
} point;
but this comes at the cost of wordier access syntax:
point p;
p.a[2] = 7;
p.s.x = 5;

Related

Creating a Set ADT in C

I am trying to create an ADT.
It is a dynamic set of finite elements. It must be implemented using arrays and linked lists.
Some operations include add(set, x) and remove(set, x).
I understand that I first need to create an interface which will be common to both the array implementation and the linked list implementation.
I am however, not sure as regards the structure for this data type. What should I include?
struct test {
int x;
char y;
};
Something like that? Or let's say that I make the set exclusive for integers, what will the data structure involve?
Help would be greatly appreciated. Thanks!
Since this is for school, I'm not going to give you an implementation, but I'll point you in the right direction. Using arrays and lists screams 'hash table'. See this answer for some good information.
For simplicity, let's assume it's a set of integers.
Essentially, you want an array hash_table of N 'buckets', i.e. lists. To add an element x, you do hash_table[hash(x) % N] to get the 'bucket' (list) x should go into, and add it to that list if it's not already in the list.
To remove x, do hash_table[hash(x) % N] to get your bucket, and remove x if it's there.
If you can implement those, search(set, x) is trivial. You can also try implementing union(setA, setB), intersect(setA, setB), difference(setA, setB), isSubset(setA, setB), etc. You may also want to peruse the Wikipedia article on the Set ADT, and do check out the entry in The Algorithm Design Manual which includes links to implementations at the bottom.
Good luck, and happy coding. If you get stuck it's always OK to ask here on SO, just post code next time. :)
This is the principle of a structure, you can put all type of variable you want in it ..
I think you want to create an array of int.
Declaring like :
int tab["number of int you want"];
And access it like that :
tab["number of case of the int you want to access"];

Data representation in C : Linked structs vs Big structs

While looking at someone's code i was struck by a way of representing data which, in a C context, seemed strange to me :
This person needed to represent different kind of geometries for a raytracer,
each geometries while being different had similarities in their structures.
So this person decided to represent the geometries through more or less abstract structs linked together through pointers.
s_entities -> s_scene_object -> s_sphere
s_entities -> s_scene_object -> s_plane
s_entities -> s_pointlight
i was wondering why one would decompose its data in C through abstraction layers instead of having an all-encompassing struct for each kind of data.
One explanation would be to reduce overhead if you have functions that operate on a certain layer of abstration of your data. right ?
it seems to me like remnants of OOP habits.
You say "remnants of OOP habits" as if that's something that's obviously not OK in C. I'd say you're wrong, there are rather large collections of very heavily object-oriented code in C. It works.
Object-orientedness is a way to arrange and model things, it's not tied to programming languages. C is low-level enough that you can do all sorts of programming paradigms in it; you'll often have to implement much of the paradigm yourself since there is little support from the language, but OO is pretty straight-forward.
It's not very clear from your example, but a more typical way to model things like that in C is by embeddeding the more basic data structure (superclass) inside the more specialized, utilizing the fact that the first member in a C struct is at offset 0 from the struct itself:
typedef struct {
float x, y, z;
} Shape;
typedef struct {
Shape shape;
float radius;
} Sphere;

How should I go about storing resources in C

What system should I use to store resources (Images, SoundEffects etc) in C?
One example would be storing them in a struct type system:
struct _Resource {
struct _Image {
SDL_Surface *MenuButton;
} Image;
struct _SoundEffect {
Mix_Chunk *MenuButtonSound;
} SoundEffect;
} Resource;
Another example would be storing them in an array:
SDL_Surface *Image[5];
Mix_Chunk *SoundEffect[5];
What are your thoughts?
There are millions of ways of doing it. Asking about what is the best way is not really constructive. You may want to see how others do it (if not re-using those components/libraries to avoid re-inventing a wheel):
GTK Resource Files
Qt Resource System
OS X bundle
Windows resource files
This question is very general, so here's the general answer:
First, you should know that struct an array are orthogonal concepts. You don't need to choose between them, you can have both.
Now usually, when you decide to have a struct, it's because the data are somehow related. For example, if you have resource that is clickable and has a position, a struct such as the following
typedef struct Resource
{
int x, y;
SDL_Surface MenuBotton;
void (*click_callback)(struct Resource *);
} Resource;
makes sense. However, if you have two unrelated concepts, such as image and sound, it absolutely doesn't make sense to put them together in one struct (unless for special cases, such as sending the pointer to a thread!)
So what you need to do is, divide different concepts and group information that are relevant to each other. Make structs out of the relevant information and create arrays of them if you have many instances of them.
In the end, you may want to have one big struct containing everything worked on by a manager of some sort, but that certainly depends on your application.

Common datastructure library in C

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?

how to program high level concepts (i.e. Object class, and Generics) in C

Here lately I've been tinkering around with my own languages as well as reading various writings on the subject.
Does anyone have any good advice on how, in C (or Assembler), do you program the concept of the Object Class and/or the concept of Generics into a language. (referring to the Java implementations of Object and Generics)
For instance, in Java all all classes extend Object. So how do you represent this at the C level? is it something like:
#include <stdio.h>
typedef struct {
int stuff;
} Object;
typedef struct {
int stuff;
Object object;
} ChildClass;
int main() {
ChildClass childClass;
childClass.stuff = 100;
childClass.object.stuff = 200;
printf("%d\n", childClass.stuff);
printf("%d\n", childClass.object.stuff);
}
And I'm not really even sure how to get started with implementing something like Generics.
I also appreciate any valuable links regarding program langauge design.
Thanks,
Take a look at Structure and Interpretation of Computer Programs by Abelson and Sussman. While it doesn't show how to do it in C, it does demonstrate how to create types at run time and how to build an object system on top of a language that doesn't provide native support. Once you understand the basic ideas, you should be able to use structs and function pointers to create an implementation. Of course, looking at the source code for a C++ preprocessor will also be instructive. At one time, C++ was just a preprocessor for a C compiler.
I found this book a little while ago that has been an interesting read: Object-Oriented Programming With ANSI-C (PDF).
In C I've created class-like structures and methods by using structs (to store the class's state) and functions that take pointers to them (methods of the class). Implementing things like inheritance is possible, but would get messy fast. I'm not a Java guy though, and I'm not sure how much of Java you should press onto C, they are very different languages.
Here's probably the crudest form of a object implementation possible; I wrote it to run multiple PID controls at the same time.
//! PID control system state variables
typedef struct {
const PID_K * K; //!< PID control parameters
int32_t e; //!< Previous error (for derivative term)
int32_t i; //!< Integrator
} PID_SYS;
void PID_Init(PID_SYS * sys, const PID_K * K)
{
sys->i = 0;
sys->e = 0;
sys->K = K;
}
int16_t PID_Step(PID_SYS * sys, int32_t e)
{
// ...PID math using "sys->" for any persistent state variables...
}
If your goal is to write a new language that incorporates high level concepts, you might want to look at the CPython sources. CPython is an object oriented programming language whose interpreter is written in C. Open source C implementations of compilers/interpreters for C++, D, Javascript, Go, Objective C, and many, many others exist as well.
It's more complicated, but you're on the right path. Actual implementations use roughly the same code as yours to achieve inheritance (but they actually use containment to do it, which is quite ironic), along with a per-instance table of function pointers (virtual functions) and some (okay, many) helper macros.
See gobject.
It's definitely not C, but I'd recommend taking a look at Lua.
At its core, Lua only has a few basic types: number, string, boolean, function, and table (there's a couple more outside of the scope of this topic, though. A table is essentially just a hashtable that accepts keys of any type and can contain values of any type as well.
You can implement OOP in Lua by way of metatables. In Lua, a table is allowed to have up to one metatable, which is accessed under special circumstances, such as when a table is added or multiplied to another table or when you try to access a key that is not present in the table.
Using metatables, you can quickly and easily achieve something quite like inheritance by chaining together multiple metatables. When you try to access a missing key in a table, Lua looks up a key named __index in that table's metatable. So if you try to access a key named foo on a table that doesn't have such a key, Lua will check for foo in the first metatable. If it isn't present there and that metatable has a metatable of its own with __index defined, it will check for foo in the next one, and so on.
Once you realize how simple it is to do this in Lua, translating it to C is very achievable. Your OOP will be completely at run-time, of course, but it will be very OOP-like indeed.

Resources