Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use pointer to single value as Array

(Note that question was extended for "register" variables)

My question in short: Is this legal C code (to the letter of the standard for the different ISO 9899 C incarantions - ideally with "proof" along the words of the standards):

int a = 0;
int b = (&a)[0];

const int c = 0;
b = (&c)[0];

Question extension: This comment by Jens Gustedt suggests that it is not allowed to take register variables' adresses. Is this true? Can one please also provide additional citation from the standards to reason about this?

/* Question extension */
register int d = 0;
int e = (&d)[0];

Background:

I have a set of arrays representing attributs of a structured collection of objects - for each attribute one array. So the arrays are linearizations of this structured collection. These attribut array elements are all compared to different values, depending on the positions of the objects in the structured collection. These values also are structured in a way that is connected with the structure od the collection :-) The attribute arrays might be each of different type.

So I wrote a macro, that iterates over all attributs (given any of the attribute arrays) and provide on the fly structure information that can be used as array index for the comparing value arrays. This macro has as input: - the attribute array - comparision predicate - the comparing value array - and the index variable name for the value array (which is used to provide the structure information in a quite complex looping within the macro) - boolean to collect the result

So you can say something like:

COMP_ALL(attr1Arr,  <=, limitbyCath1Arr, cath1Idx, anyLimitFault)

and somewhere in the deep looping that linearizes over different categories you find a comparison like:

anyLimitFault = anyLimitFault 
                  && (attr1Arr[objCounter]  <= limitbyCath1Arr[cath1Idx]);

Now sometimes there is just one limit value so I want to write:

int limit = -1;
COMP_ALL(attr4Arr, <=, (&limit), 0, anyLimitFault);

Of course I could always do:

 int limit = -1;
 int temp[1];
 temp[0] = limit;

 COMP_ALL(attr4Arr, <=, temp, 0, anyLimitFault);

But I would prefer the other way, so I can encapusate to:

 COMP_ALL2Value(attr_arr, pred, val, collector) \
      COMP_ALL(attr_arr, pred, (&val), 0, collector)
like image 939
Mark A. Avatar asked Oct 17 '25 10:10

Mark A.


1 Answers

Yes. &a in your example can be treated as a pointer to the first element of an one-element array.

C99 / C11 §6.5.6 Additive operators section 7

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

like image 74
Yu Hao Avatar answered Oct 20 '25 01:10

Yu Hao