I was wondering, in Processing, how to include an array as part of an object. Say I have an Object named "Node" and want it to contain a list of all the IDs of other nodes it's connected to. Please note that the length of this list can be variable. That is, one node can be connected to two or seven different other nodes. And how would I access that particular array within that object?
Here's some code I'm working with:
void setup(){
size(200,200);
Node node1 = new Node(color(255,0,0),40,80,2,0,.5,5,5,0);
int neighbor = 6;
node1.neighbors.add(neighbor);
}
void draw(){
}
class Node {
Set<Node> neighbors;
color c;
float xpos;
float ypos;
float xspeed;
float yspeed;
float damp;
float ForceX;
float ForceY;
int id;
// The Constructor is defined with arguments.
Node(color tempC, float tempXpos, float tempYpos, float tempXspeed, float tempYspeed, float tempDamp, float tempForceX, float tempForceY, int id_temp) {
c = tempC;
xpos = tempXpos;
ypos = tempYpos;
xspeed = tempXspeed;
yspeed = tempYspeed;
damp = tempDamp;
ForceX = tempForceX;
ForceY = tempForceY;
id = id_temp;
neighbors = new HashSet<Node>();
}
}
Thanks!
Arrays can be included in a class just as any other var:
class Node{
int[] array;
Node (int[] _array){
array = _array;
}
/// all he stuff
}
But i think an object can't be "aware" of others objects of the same type. Maybe you need an other class Nodes, that takes an array of Node at constructor, or an ArrayList as the size must be variable. Or i'm afraid you have to handle the set of Node in draw().
You're describing a graph. A graph class should look like this:
class Node {
Set<Node> neighbors = new HashSet<Node>();
}
You may want to create methods such as addNeighbor(Node neighbor), isNeighbor(Node x) { return neighbors.contains(x); }, etc.
You described ids, but this method is more efficient assuming you have to load the other nodes in memory. The Set here containers references (e.g. C++ pointers) to other nodes.
You could also do a Set if you want ids and only integers.
Related
I'm creating a struct like this:
typedef struct stat{
char name[50], type[50];
double x, y, lar, alt;
} info;
typedef struct list{
int prim, livre;
info A[];
} LS;
int main(){
int n;
scanf("%i", &n);
LS *mylist = malloc(sizeof(LS) + n);
mylist->info->A[3] = 1.5;
printf("%lf", mylist->info->A[3]);
return 0;
}
I know it's possible to create a flexible array type inside a struct, however i don't know how can i access the array to use it. How should i do that and how it would work for strings?
I want to use an array(which size will be defined by the user input) and inside of it i will store a struct with name, type, x, y, lar, alt in position A[0], another in position A[1] and so on.
You access a flexible array member exactly like any other structure member.
In your case you access it as mylist->A, and each individual element of the array as info->A[i] (for valid values of i).
Then since each element of the array is a structure object use use normal dot-notation . to access the members of the structures in the array:
mylist->A[3].x = 1.5;
printf("%f\n", mylist->A[3].x);
I'm adding the next bit to this silly assignment of mine, and I'm modifying my old code now that I'm implementing these 'Linked List' things, but I can't figure out how you pull data out of them?
So, the software needs to pull the variables for whatever planet you're up to in the list, and assign the numbers to the variables, if that makes sense?
typedef struct Planet
{
char Planet_Name[30];
double Fuel;
double Velocity;
double Height;
double Gravity;
int Maximum_Thrust;
double Difficulty;
}Planet_t;
typedef struct PlanetNode
{
Planet_t* planet_Name;
struct PlanetNode* next;
}PlanetNode_t;
typedef struct PlanetList
{
PlanetNode_t* head;
int count;
}PlanetList_t;
(in main)
PlanetList_t* SolarSystem = calloc(1, sizeof(PlanetList_t));
printf("The Planets are (with their corresponding difficulty level)
Pluto[0], Moon[1], Mercury[2], Mars[3].....
double height = SolarSystem->head->Height;
double velocity = SolarSystem[PlanetNum]->Velocity;
double fuel = SolarSystem[PlanetNum]->Fuel;
double gravity = SolarSystem[PlanetNum]->Gravity;
double fuelBurn;
double difficulty = SolarSystem[PlanetNum]->Difficulty;
So basically, I need to figure out that last bit. Each iteration of the program changes the selected planet (linearly going through the planets), so the variables need to be renewed each time.
I'm trying to implement a coordinate system for a player in a game.
I have a struct
typedef struct player {
int playerPosition[1][5];
}
I create a pointer to that struct
struct* player playerPtr;
struct player playerOne;
playerPtr = &playerOne;
If during the game, I want to update the coordinate of the player to position [1,2].
I get errors when I use playerPtr->playerPosition=[1][2];
What's the correct way of doing this?
As written, you could do this:
playerPtr->playerPosition[0][2] = 100;
But probably you have an error here:
int playerPosition[1][5];
Because it rarely makes sense to have an array of size 1. Did you really mean for playerPosition to be a 1x5 array of ints? It looks like you wanted something like this:
struct position {
int x, y;
};
struct player {
position playerPosition;
};
Then you would do this:
playerPtr->playerPosition.x = 1;
playerPtr->playerPosition.y = 2;
playerPtr->playerPosition=[1][2]; will give you error (syntactically wrong)
you are not specifying the array index at which the data is to be stored, also you cant store data by that way in C.
correct way would be:
playerPtr->playerPosition[0][0] = 1;
playerPtr->playerPosition[0][1] = 2;
.
.
.
playerPtr->playerPosition[9][0] = 19;
playerPtr->playerPosition[9][1] = 20;
which is valid if you declare your array like this:
int playerPosition[10][2];
which will allow you to store ten coordinates.
2Dimentional arrays such as array[1][10] are same as array[10] (for usage, I am not certain about memory allocation, 2D array might require more memory)
I think you could use different but easier approach to this problem:
typedef struct position{
int x, y;
float refpos; //position from some reference point (like healing circle)
}position;
typedef struct player{
char name[20];
int health, attack, defense; //can be float too
position coord[20];
}player;
player player1, *playerPtr;
playerPtr = &player1;
playerPtr->position[0].x = 3;
playerPtr->position[0].y = 4;
playerPtr->position[0].refpos = 5; //Pythagorean triplet wrt origin (0,0)
Prost !
Hello I have following code.
typedef struct __vector {
int (*container_end) ( struct __vector *);
}vector;
and another iterator structure with following declaration :
typedef struct __iterator {
void *ptr_to_container;
int (*end)(struct __iterator *);
}iterator;
int
end(iterator *itr) {
return (itr->ptr_to_container)->container_end(itr->ptr_to_container);
}
This code does not compile as ptr_to_container is void pointer.
Is there any work-around to this problem.
container_end function will be defined separately and ptr_to_container will point to some container.
thanks
Avinash
It looks like you have missed something when defining the iterator structure. Why does the iterator have a function pointer to an 'end' function that accepts an iterator?
If you want it to be really generic, you could perhaps use this definition instead:
typedef struct __iterator {
void * ptr_to_container;
int (*end)(void *);
} iterator;
int end(iterator * it) { return it->end(it->ptr_to_container)); }
In the vector definition (and other data types), you can then define a function to create an iterator:
static int vector_end(vector * v) { /* implementation omittted */ }
iterator * vector_create_iterator(vector * v)
{
iterator * it = malloc(sizeof(iterator));
it->ptr_to_container = v;
it->end = vector_end;
return it;
}
However, the solution really depends on how the data structures are defined. In the above suggestion, it is up to each data structure to provide an implementation for how to traverse it.
As an alternative, you could set up a generic data structure interface, like
typedef struct _container container;
struct _container {
int (*end)(container * c);
};
Then the vector implementation would "only" have to fill in this container structure:
typedef struct _vector {
container c;
/* other fields required by the vector */
}
static int vector_end(container * c)
{
vector * v = (vector *) c;
...
}
container * create_vector()
{
vector * v = malloc(sizeof(vector));
v->c.end = vector_end;
return v;
}
...and the iterator could work with just the generic container:
typedef struct _iterator {
container * c;
/* other fields used by the iterator, such as current position */
}
int end(iterator * it) { return it->c->end(it->c); }
From the code sample in the question, it looks almost like you have mixed up these two approaches :-)
Did you try casting to a vector *?
return ((vector *)(itr->ptr_to_container))->containter_end(itr->ptr_to_container);
However, are you sure you want to do this? You are using itr to call a function and then pass itr to that function. Including more context (more code) would help.
You need to explicitly cast *ptr_to_container to a vector pointer:
((__vector *)(itr->ptr_to_container))->container_end
Otherwise the compiler doesn't know what is the structure of the target.
Though, I don't really see why you want to have such a construction. It looks like you want to have object orientation here with inheritance, but without explicitly stating anything. It won't work well. In C, you'll have to use less general structures, or move to C++.
If it must be void * use
int
end(iterator *itr) {
return ((vector)(itr->ptr_to_container))->container_end(itr->ptr_to_container);
}
or else specify in the iterator that it is a vector iterator
typedef struct __iterator {
vector *ptr_to_container;
int (*end)(struct __iterator *);
}iterator; //probably you'll need to rename to make type of iterator clear
If you need to keep the abstraction (one iterator for all of you containers) nothing comes to mind atm...
I have two identical (but differently named) C structures:
typedef struct {
double x;
double y;
double z;
} CMAcceleration;
typedef struct {
double x;
double y;
double z;
} Vector3d;
Now I want to assign a CMAcceleration variable to a Vector3d variable (copying the whole struct). How can I do this?
I tried the following but get these compiler errors:
vector = acceleration; // "incompatible type"
vector = (Vector3d)acceleration; // "conversion to non-scalar type requested"
Of course I can resort to set all members individually:
vector.x = acceleration.x;
vector.y = acceleration.y;
vector.z = acceleration.z;
but that seems rather inconvenient.
What's the best solution?
That's your only solution (apart from wrapping it into a function):
vector.x = acceleration.x;
vector.y = acceleration.y;
vector.z = acceleration.z;
You could actually cast it, like this (using pointers)
Vector3d *vector = (Vector3d*) &acceleration;
but this is not in the specs and therefore the behaviour depends on the compiler, runtime and the big green space monster.
You could use a pointer to do the typecast;
vector = *((Vector3d *) &acceleration);
memcpy(&vector, &acceleration, sizeof(Vector3d));
Please note that this works only, if the physical layout of the structs in memory are identical. However, as #Oli pointed out, the compiler is not obliged to ensure this!
You use an utility function for that:
void AccelerationToVector( struct CMAcceleration* from, struct Vector3d* to )
{
to->x = from->x;
to->y = from->y;
to->z = from->z;
}
Why dont you use.
typedef CMAcceleration Vector3d;
(instead of creating a whole new structure)
in that case vector = acceleration; compiles just fine.
Another version of the utility function making use of C99:
static inline struct Vector3d AccelerationToVector(struct CMAcceleration In)
{
return (struct Vector3d){In.x, In.y, In.z};
}
With the compiler optimization turned up (e.g., -Os), this should turn into absolutely no object code when invoked.
This is achieved easily through a union:
typedef struct {
double x;
double y;
double z;
} CMAcceleration;
typedef struct {
double x;
double y;
double z;
} Vector3d;
typedef union {
CMAcceleration acceleration;
Vector3d vector;
} view;
int main() {
view v = (view) (Vector3d) {1.0, 2.0, 3.0};
CMAcceleration accel = v.acceleration;
printf("proof: %g %g %g\n", accel.x, accel.y, accel.z);
}
A safe (albeit somewhat convoluted) way to do it would be to use a union:
union { CMAcceleration a, Vector3d v } tmp = { .a = acceleration };
vector = tmp.v;
Values are reinterpreted (since C99) when the accessed member is not the last set one. In this case, we set the acceleration and then we access the vector, so the acceleration is reinterpreted.
This is the way the NSRectToCGRect function is implemented, for example.
You could create a union with pointers that way you avoid copying data.
example :
struct Ocp1SyncHeader
{
aes70::OCP1::OcaUint8 syncVal;
aes70::OCP1::Ocp1Header header;
};
struct convertToOcp1SyncHeader
{
union
{
Ocp1SyncHeader* data;
const uint8_t* src;
};
convertToOcp1SyncHeader& operator=(const uint8_t* rvalue)
{
src = (const uint8_t*)rvalue;
return *this;
}
};
** access like this:
convertToOcp1SyncHeader RecvData;
RecvData = src; // src is your block of data that you want to access
** access members like this :
RecvData.data.header