Pointers in C
You,•C Programming
Addresses and pointers in C
Let us declare a single variable and array, and see how they are placed in memory
/* Online C Compiler and Editor */
#include <stdio.h>
int main()
{
printf("Declaring an integer and an integer array\n");
int num=7853;
int d[3] = {1,2,7};
printf("num= %d\n",num);
for(int i =0;i<3;i++)
printf("Integer array element d[%d] = %d\n",i,d[i]);
int * pd = d;
printf("addresss of d = %ld\n",pd);
int * pd0 = &(d[0]);
printf("addresss of d[0] = %ld\n",pd0);
int * pe = d+1;
printf("addresss of e = %ld\n",pe);
int * pd1 = &(d[1]);
printf("addresss of d[1] = %ld\n",pd1);
return 0;
}
Output:
Declaring an integer and an integer array
num= 7853
Integer array element d[0] = 1
Integer array element d[1] = 2
Integer array element d[2] = 7
addresss of d = 140727830638268
addresss of d[0] = 140727830638268
addresss of e = 140727830638272
addresss of d[1] = 140727830638272
Notes:
- The address of a variable is the location of it's first byte
- Pointers and arrays are closely related
- The address of a variable can be stored in another variable
- Addresses must be stored in special types of variables
- In C language,these special variables called pointers.
- the C compiler does not allow to store pointers in normal integers/long variables
- this is possible to trick the compiler via casting etc, but this is not reccomended.
- By storing addresses in 'pointer' variables,
- C language knows the value is a pointer and treats it in special ways
- C language also takes into account, the 'size' of the data type held in a pointer
- Recap: Addresses and pointers:
- Address is the location.
- Pointer is a variable that stores the location.
- if d is an array (of any type), say int d[10];
- then the address of d and address of d[0] are the same
- the first element of the array
- can be written as: d[0]
- can also be written as: *(d) or *d
- i.e. *(d) refers to first element, not entire array
- you can think of operator * as "content-of"
- the array indices in above case starts at 0 and ends at 9 (not 10)
- the nth element of the array
- can be written as d[n]
- can also be written as *(d+n)
- Adding index n to d produces address of d[n]
- this means the content of *(d+n) and d[n] all point to the same value
- C is aware if array contains 'integers' or 'char' or 'double'
- C is aware of the byte size of each of these variables
- to get address of [n] the element,
- C compiler does not simply add n to d (i.e. d+n)
- instead, it adds (sizeof int)* n to d.