overduekey
overduekey

Reputation: 51

Finding if element is within a specified Array

I am trying to find if a ptr points to an element within the specified intArray. It is to return 1 if true and 0 if false.

Please see code.

int withinArray(int * intArray, int size, int * ptr) {

 int length = ptr - intArray;
 int signal = length >> 31;

  //size
  int size1 = (size - 1 - length) >> 31;


  return (signal | size1) + 1;

}

The program works. HOWEVER, I am not allowed to use the Binary integer operators: &, &&, |, ||, <, >, !=, /, % or Unary: ~ or Pointer operators: []. My solution so far required that I use the | symbol (see return statement). Is there anyway I can work around this? I have tried several other ways and all include the | or & symbol which are not allowed. I have been stuck on this for a while now and cannot think of a way around this.

Upvotes: 0

Views: 942

Answers (2)

monish_koppa
monish_koppa

Reputation: 341

I see you are not allowed to use the operators: &, &&, |, ||, <, >, !=, /, % or Unary: ~ or Pointer operators: [].

But can you use == operator? If yes, then the below solution will work for you.

int withinArray(int * intArray, int size, int * ptr) {
while(size--) {
    if(intArray == ptr) return 1;
    intArray++;
}
return 0;
}

Hope this helps :)

Upvotes: 2

chux
chux

Reputation: 154075

OP's Code relies on undefined behavior (UB).

Pointer subtraction ptr - intArray is UB if ptr is not in the array (or one pass the end).

Code could compare again each element one at a time. Inefficient, but not UB.

Perhaps:

 // not allowed to use the Binary integer operators:&, &&, |, ||, <, >, !=, /, % or Unary: ~
int withinArray(int * intArray, int size, int * ptr) {
  while (size >= 1) {
    // Unclear if ==, ++ this counts for OP as a "Pointer operator"
    if (intArray == ptr) return 1;
    intArray++; 
    size--;
  }
  return 0;
}

Code could attempt to convert the pointer to integers of sufficient range if available (pointers can readily exceed 32-bit int or even 64-bit) and then attempt an integer computation/compare. Yet even that is not portable as 2 pointers that convert to 2 different integers may still point to the same address with non-linear address models.

Upvotes: 2

Related Questions