How to use array pointer

Arrays and pointers

The address of an array is represented by the array name.


#include <stdio.h>
/*from  w w  w . java 2 s .c  o m*/
void main()
{
   char multiple[] = "I am a string";

   printf("\nThe address of the first array element  : %p", &multiple[0]);
   printf("\nThe address obtained from the array name: %p\n", multiple);
}

The following code accesses the first element in an array by using both array index and array pointer.


#include <stdio.h>
/*from   w w w .  ja  v  a  2  s.  c o m*/
void main()
{
   char s[] = "a string";

   printf("value of second element: %c\n", s[1]);
   printf("value of s after adding 1: %c\n", *(s + 1));
}

The name of an array is the same as &array[ 0 ].


#include <stdio.h>
//from   w w  w.j  ava 2 s .  com
int main()
{
   char array[ 5 ]; 

   printf( "    array = %p\n&array[0] = %p\n"
      "   &array = %p\n",
      array, &array[ 0 ], &array );

   return 0; 

} 

The code above generates the following result.

The following code uses the same techniques to get the address of an array.


#include <stdio.h>
/*from  w ww. j a  v a2s  .c om*/
int main(void)
{
  char multiple[] = "My string";

  char *p = &multiple[0];
  printf("\nThe address of the first array element  : %p", p);

  p = multiple;
  printf("\nThe address obtained from the array name: %p\n", p);

  return 0;
}

The code above generates the following result.

When the pointer is incremented by an increment operator, it is always right incremented and points to the next value.


#include <stdio.h>
/*from  w  ww . j  a v  a2s  .c  om*/
main(){
    int a[5];
    int i;
    for(i = 0;i<5;i++){
        a[i]=i;
    }

    int *b;
    b=a;
    for(i = 0;i<5;i++)
    {
        printf("value in array %d and address is %16lu\n",*b,b);
        b++;                 
    }
}

Pointer subscript notation vs Pointer/offset notation

Pointer subscript notation


#include <stdio.h>
//  w ww  . j a v a2  s. com
int main()
{
   int b[] = { 10, 20, 30, 40 }; 
   int *bPtr = b;                
   int i;                        
   int offset;                   

   for ( i = 0; i < 4; i++ ) {
      printf( "bPtr[ %d ] = %d\n", i, bPtr[ i ] );
   } 

   return 0;
}

The code above generates the following result.

Pointer/offset notation


#include <stdio.h>
/*from w ww  .j  av  a 2  s  .  c  om*/
int main()
{
   int b[] = { 10, 20, 30, 40 }; 
   int *bPtr = b;                
   int i;                        
   int offset;                   


   for ( offset = 0; offset < 4; offset++ ) {
      printf( "*( bPtr + %d ) = %d\n", offset, *( bPtr + offset ) );   
   } 

   return 0;
}

The code above generates the following result.





















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing