user1386132
user1386132

Reputation: 27

Bit vector implementation from a given array

I'm trying to create a bit vector set from a given array. Not sure how to start it off. For example given the array: int rows[] = {1, 2, 5} I need to make a function unsigned short MakeBitVector(int values[], int nValues) You're allowed to assume that the range for the elements in the array is 1-9. Here's what I have so far:

unsigned short MakeBitVector(int values[], int nValues)
{
  (55)unsigned short int set = calloc(nValues, sizeof(unsigned short));
  for(int i = 0; i < nValues; i++){
    (57)set[i] = values[i];
  }
  return set;
}

I keep getting warnings and errors:

bits.c:55: warning: initialization makes integer from pointer without a cast

bits.c:57: error: subscripted value is neither array nor pointer

Any ideas on how to fix this?

Upvotes: 1

Views: 2729

Answers (3)

Peter
Peter

Reputation: 7324

I don't think you need dynamic allocation at all; calloc is just confusing things. Also, you will need to operate on single bits somewhere which your code isn't at present. What about this:

unsigned short MakeBitVector(int values[], int nValues) {
  unsigned short int set = 0;
  for(int i = 0; i < nValues; i++){
    set |= 1 << values[i];
  }
  return set;
}

Obviously the output of this is undefined if the input contains indices >= 16, but you said that shouldn't be a problem (and you could easily extend it to 32 anyway).

Upvotes: 2

Vlad
Vlad

Reputation: 35594

You definitely need your set to be a pointer:

unsigned short int* set = calloc(nValues, sizeof(unsigned short));

And you have to change the return type of the function to pointer as well.

Edit: if you want to pack everything into one int, you can go on in a simpler way:

unsigned short MakeBitVector(int values[], int nValues)
{
    unsigned short int set = 0;
    for (int i = 0; i < nValues; i++)
        set |= 1 << values[i];
    return set;
}

You don't need to allocate a single int, returning the copy is just fine.

Upvotes: 4

Makoto
Makoto

Reputation: 106430

set isn't a pointer. Change that to a pointer instead. You would also need to return a pointer as well.

Upvotes: 0

Related Questions