SYM2RR
SYM2RR

Reputation: 31

error: expression must have pointer-to-object type

I tried to design a program that will return the original 32bit value w but change the number i element to 1. Here's the function I got so far. But for this part, v[i]=1; , it just says that for i expression must have pointer to object type.

 unsigned int setBit(unsigned int w,unsigned int i)
 {
    unsigned int v = w;
    v[i]=1;
    return v;
 }

Upvotes: 0

Views: 9432

Answers (3)

4pie0
4pie0

Reputation: 29724

unsigned int v = w;
v[i] = 1; // error, v is not an array

This is not correct because v is not an array. The solution might be using a std::bitset or simply shifting bits and using some bit manipulation - this would be faster.

unsigned int setBit(unsigned int w,unsigned int i) {
    unsigned int v = ( w |= 1 << i);
    return v;
}

usage:

int main(int argc, char *argv[])
{
    unsigned int in = 0;
    unsigned int res = setBit(in,1); // set 1st bit in 0 to 1, results in 2
    return 0;
}

meaning of unsigned int v = ( w |= 1 << i);

| - the bitwise OR

<< - the bitwise shift

v = ( w |= 1 << i) is the same as v = ( w = w | 1 << i) so it means: v is equal to (take w and OR it with 1 left shifted by i, and assign this to w)

about C/C++ bit manipulation

Upvotes: 2

Aesthete
Aesthete

Reputation: 18850

In case you're interested.

unsigned int setBit(unsigned int w, unsigned int i)
{
  std::bitset<sizeof(unsigned int)> bitset((unsigned long long)w);
  bs.set(i, 1);
  (unsigned int)return bs.to_ulong();
}

Although I would still use piotrus' answer.

Upvotes: 0

herohuyongtao
herohuyongtao

Reputation: 50657

In C++, [] operator is for string/array/vector/map/..., but not for a unsigned int.

For your example, you probably need to change it to bit array first to be able to use such way.

Upvotes: 0

Related Questions