Thread: changing arr[0] to arr[1]

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    36

    changing arr[0] to arr[1]

    Here's what I mean

    Code:
    void dectobin (int * arr, unsigned char b)
    {
        arr[0] = (b & 128) ? 1 : 0;
        if (b) dectobin (&arr[1], b << 1);
    }
    &arr[1] is what I'm mostly concerned about. I tested it out in some code:
    Code:
    void testarray (int arr[])
    {
        arr[0] = 255;
    }
    
    // ...
    
    for (int i = 0; i < 8; ++i)
        {
            testarray(&testarr[1]);
        }
    for (int i = 0; i < 8; ++i)
        {
            cout << "[" << i << "]: " << testarr[i] << endl;
        }
    Indeed it did what I thought it would. Inside the function arr[0] is actually arr[1] because &testarr[1] makes arr[0] == arr[1]... wait, what?? Can someone explain to me the behind the scenes? The best explanation I have is &testarr[1] sets the address of arr[0] as arr[1]. My brain is stuck in an infinite loop of sorts. BTW, yes I know what the main code is, and fairly understand bitwise operations and truth tables.
    Last edited by Darkroman; 09-01-2013 at 02:14 AM. Reason: Fixed up some typos.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It doesn't make any difference to testarray, it's just a pointer to an int.
    The fact that you made the parameter as int arr[] doesn't convey any extra arrayness properties.

    You could do this.
    Code:
    int array[10];
    int val;
    int *p = malloc(10,sizeof(*p);
    
    // Then any of these
    testarray(array);
    testarray(&array[0]);
    testarray(&array[1]);
    testarray(&val);
    testarray(p);
    testarray(&p[0]);
    testarray(&p[1]);
    Just make sure the function in question doesn't try to access beyond the bounds of the supplied parameter.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Changing the key
    By maxorator in forum Windows Programming
    Replies: 7
    Last Post: 09-23-2006, 12:55 AM
  2. Changing windows without changing?
    By Lionmane in forum Windows Programming
    Replies: 7
    Last Post: 10-19-2005, 11:41 AM
  3. Changing my name
    By Salem in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 02-15-2005, 12:24 PM
  4. Changing X
    By SpEcIeS in forum Windows Programming
    Replies: 2
    Last Post: 01-01-2005, 03:57 PM
  5. Changing IP
    By NotTaken in forum Windows Programming
    Replies: 1
    Last Post: 01-30-2003, 10:03 PM