1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

choosen random value

Discussion in 'C' started by fulla, Mar 7, 2011.

  1. fulla

    fulla New Member

    Joined:
    Mar 6, 2011
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    hi..

    if I want choose a random value that have 0 or 1 just

    HTML:
     rand() & 1;
    
    
    is it correct ??

    thanks..
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    What happens if you try it?
     
  3. fulla

    fulla New Member

    Joined:
    Mar 6, 2011
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    its work good but relly i dont understand whay !!

    I have aprublem ..

    i declerat apointer to pointer variable..

    then I wan but this variable=null;
    I got error I dont know whay??

    ex:
    int **T;
    *T= NULL;

    is this an error ??
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    The rand() works because & is a bitwise operator, so &1 just takes the least significant bit. Look at the binary for the return value; if the results of rand() are, say, 10,5,3,17,6,4,21 then the LSB for those results are 0,1,1,1,0,0,1.

    *T=NULL is an error because you haven't defined *T anywhere. When you create a pointer, you allocate space for the pointer itself but you don't allocate space for what that pointer points to. So when you write to *T, after defining just int **T, you're writing NULL to an unknown location in memory.

    So if you do:
    int T;
    int *pT=&T;
    int **ppT=&pt;

    THEN you can write to T, *pT and **ppT.
     
    fulla likes this.

Share This Page