Array indexing starting at a number not 0

后端 未结 13 2365
Happy的楠姐
Happy的楠姐 2021-02-20 04:02

Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[

13条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 04:51

    As others have noted, you can technically achieve what you want by invoking pointer arithmetic like this:

    int* myArray = malloc((upperBound - lowerBound) * sizeof(*myArray));
    myArray -= lowerBound;
    ...
    for(int i = lowerBound; i < upperBound; i++) {
        myArray[i];
    }
    

    While this will work flawlessly with -O0, it is undefined behaviour from a language point of view. The machine, however, has absolutely no objections to this, to the machine the pointer arithmetic involved is the same as any unsigned integer arithmetic with uintptr_t. Thus, the only danger to this approach is the optimizer.

    Now, you can easily defeat the optimizer by splitting the code above into two different compilation units, i. e. have one ".c" file with the function

    int* fancyIntArray(size_t lowerBound, size_t upperBound) {
        return intMalloc(upperBound - lowerBound) - lowerBound;
    }
    

    and put the function intMalloc() into a different ".c" file:

    int* intMalloc(size_t size) {
        return malloc(size_t*sizeof(int));
    }
    

    Now, you are safe, because when the optimizer looks at the pointer arithmetic in fancyIntArray(), it does not know that there is no allocated memory in front of the address that intMalloc() returns, as it does not know anything about intMalloc() itself. As such, it is forced to leave your code intact.

    And, of course, you should use independent compiler calls to compile the different ".c" files, so that the optimizer really cannot deduce anything about intMalloc().

提交回复
热议问题