I have an array of structs, and I have some functions that will be using several of the members of those structs. I would like to avoid the dereference in every line. I would think that there would be some way to declare a variable at a certain memory location… something like:
someStruct &myStruct = arrayOfStructs[i];
myStruct.x = foo+bar*myStruct.y*myStruct.w;
//Instead of myStruct->x = foo+bar*myStruct->y*myStruct->w;
//It would/should even be possible to access the members in a similar way:
int &x = &myStruct.x;
x = x+4*y+2*z;
//This should avoid overhead of dereferencing the pointer, and offsetting to the member
//by just accessing that particular address of memory as though it was where the variable
//had always been.
This bit of example code may help explain:
#define NUM_BIGSTRUCTS 10000
typedef struct {
int a,b,c;
float d,e,f;
} bigStruct;
bigStruct* arrayOfStructs;
void foo() {
for(int i=0; i<NUM_BIGSTRUCTS; i++) {
bigStruct* temp = arrayOfStructs[i];
temp->f = (temp->d+temp->e)*((float)temp->a+temp->e);
//more similar, with conditionals, etc...
//actually I've got nested loops, and a very very large array
//so any gains per inner loop would decrease my number of instructions exponentially
//So, if I could declare a bigStruct and set its address to the location of a bigStruct in the array
//then I could avoid a dereference every time I access a member of that bigStruct
//Leaving just the member access overhead... which could be handled in a similar manner
//if possible, and when appropriate
}
}
int main(int argx, char** argv) {
arrayOfStructs = g_new0(bigStruct,NUM_BIGSTRUCTS); //Allocate and 0 memory for simplicity
foo();
return 0;
}
I never have had great success on SO, so hopefully I explained what I’m trying to do. I’m using C99 btw, and I would believe it’d be possible given the low level nature of c.
[edit]
Looks like I was looking for ‘References’ from C++, but for C. Even so, they only allow assignment once(initialization), which wouldn’t work in my example. I’ve decided to rely on the compiler to optimize away multiple accesses to the same section of memory.
Thanks,
James Newman
You’re attempting something that the compiler optimization does much better than you can do manually. Also, C99, does not have these referencing constructs the way you are attempting to define them in your example—specifically the C++ dereferencing declarations—if you’re also getting really big and deep, I suggest that you rethink your algorithm. If you attempt to introduce a number of temporary variables and more memory around to do referencing you are going to make your life harder.
For instance if you look at:
process1 and process2 generate identical assembly outputs using gcc -O2 on x86_64 platform: