Array indexing starting at a number not 0

后端 未结 13 2362
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:56

    I remember reading in the book 'Expert C Programming - Deep C Secrets', Peter Van der Linden discloses a trick to fool the compiler into thinking array offsets starts at 1...theoretically the trick can be accomplished, I do not have the book with me, but offhand, I recall reading it...it is not portable and may produce undefined behavior...

    Edit: See here section 6.17 on the C-FAQ. WARNING: Not Portable and Undefined behavior! To quote from the source here.

    6.17: Here's a neat trick: 
          if I write int realarray[10]; 
             int *array = &realarray[-1]; 
    I can treat "array" as if it were a 1-based array. A: Although this technique 
    is attractive (and was used in old editions of the book _Numerical Recipes in C_), 
    it is not strictly conforming to the C Standard. Pointer arithmetic is defined 
    only as long as the pointer points within the same allocated block of memory, 
    or to the imaginary "terminating" element one past it; otherwise, the behavior 
    is undefined, *even if the pointer is not dereferenced*. The code above could 
    fail if, while subtracting the offset, an illegal address were generated 
    (perhaps because the address tried to "wrap around" past the beginning of some 
    memory segment). 
    
    References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6; 
    ISO Sec. 6.3.6; Rationale Sec. 3.2.2.3.
    
    Read more: http://www.faqs.org/faqs/C-faq/faq/#ixzz0ftyqHOvm
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题