user654761
user654761

Reputation: 117

Operation on Array Address

I do not know whether my question is appropriate or not. If there is a code....

int a[2];

If I want to check &a[0]%8==1 and do the operation a[0]= (a[0] & ~7), is this valid way of doing?

Upvotes: 0

Views: 246

Answers (1)

Jens
Jens

Reputation: 72667

It is not you who gets to decide the address of an array, it's the compiler+linker to decide at compile+load-time. (And you cannot assign to arrays, only to elements of arrays.)

If you need suitably aligned memory, use the malloc() function from <stdlib.h>. The C language standard guarantees that the pointer returned by malloc is suitably aligned for any type. If the minimum requirements for any type is 8, this will be an 8-byte aligned pointer. So what you should do is:

  #include <stdlib.h>

  int main (void)
  {
      int *a;

      a = malloc (2 * sizeof(*a));
      if (a == NULL) { /* Handle out of memory. */ }
      /* ... */
  }

This is actually a bit of overkill, since an array-of-int declared with int a[2]; will very likely have an alignment supporting fastest operation. Why is it you think forcing 8-byte alignment would be advantageous?

Upvotes: 3

Related Questions