Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming (aliasing) array elements C

Tags:

c++

c

Not sure what is "good practice" or considered more "correct". I have an array, I want to access individual elements by names other than arrayname[]. I could use #defines or pointers, probably other ways also.

Example:

#define value1 myarray[1]

int myarray[SIZE];
value1 = 5;

or

int myarray[SIZE];
int *ptr;
ptr = &myarray[1];
*ptr = 5;

Seems to me the #define route is simpler and uses less memory, but could bring up a bunch of issues I am not aware of. Any insight would be great, I like to keep my code following the general accepted standards wherever possible.

*Edit:Maybe there is a better way altogether. My end goal is to get an array that will be sent out a peripheral port. However the data is comprised of very different data sets, and a single array name would not be representative of the data being assigned. My memory is quite limited so I would like to avoid double storing each value.

like image 676
abrand Avatar asked Jan 15 '23 18:01

abrand


2 Answers

I propose a third option, by example:

#define VALUE1_IDX  1

int myarray[SIZE];
myarray[VALUE1_IDX] = 5;

The advantage of this over #1 is that it's still obvious that you're making use of myarray, and the advantage over #2 is, like you said, avoiding pointers. I would suspect, but haven't verified, that with optimization there is going to be no extra memory usage with option #2, despite that it seems intuitive that it would.

I think the best solution will vary with the situation, and I think either of your two options could be defensible in the right context.

Edit: To echo Kevin's comment, it's also first worth checking if it's possible to avoid using an array when you're not handling the values collectively. I realize that there are certainly situations where this does not apply, such as if you read in a long message and want to simply pull out a couple of key values.

like image 190
David Duncan Avatar answered Jan 21 '23 08:01

David Duncan


Why not references?

int A[3];  
int& a1=A[1];
like image 20
Leonid Volnitsky Avatar answered Jan 21 '23 08:01

Leonid Volnitsky