Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to [-1]th index of array

How does a pointer points to [-1]th index of the array produce legal output everytime. What is actually happening in the pointer assignment?

#include<stdio.h>
int main()
{
        int realarray[10];
        int *array = &realarray[-1];

        printf("%p\n", (void *)array);
        return 0;
}

Code output:

manav@workstation:~/knr$ gcc -Wall -pedantic ptr.c
manav@workstation:~/knr$ ./a.out
0xbf841140

EDIT: If this scenario is valid, then can i use this to define an array whose index start from 1 instead of 0, namely: array[1], array[2],...

like image 728
manav m-n Avatar asked Mar 02 '10 09:03

manav m-n


People also ask

Is array index a pointer?

So expression *(p+1) has type int. Since p[1] abbreviates *(p+1), p[1] has type int. It is the item in array p at index 1. An array is a pointer, and you can store that pointer into any pointer variable of the correct type.

How do you find the pointer to the first element of an array?

The process begins by making a copy of the pointer that points to the array: int *ptr = A; // ptr now also points to the start of the array. This pointer points to the first element in the array. You can dereference that pointer to access the array element.

Can pointers be indexed?

The C++ language allows you to perform integer addition or subtraction operations on pointers.

What is pointer to an array?

When we allocate memory to a variable, pointer points to the address of the variable. Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable.


2 Answers

a[b] is defined as *(a+b)

therefore a[-1] is *(a-1)

Whether a-1 is a valid pointer and therefore the dereference is valid depends on the context the code is used in.

like image 176
Šimon Tóth Avatar answered Oct 21 '22 10:10

Šimon Tóth


Youre simply getting a pointer that contains the address of that "imaginary" location, i.e. the location of the first element &realarray[0] minus the size of one element.

This is undefined behavior, and might break horribly if, for instance, your machine has a segmented memory architecture. It's working because the compiler writer has chosen to implement the arithmetic as outlined above; that could change at any moment, and another compiler might behave totally differently.

like image 43
unwind Avatar answered Oct 21 '22 10:10

unwind