Showing posts with label Pointer. Show all posts
Showing posts with label Pointer. Show all posts

Pointer to Array of Pointers in C

C Code for pointer to array of char* ie pointer to strings.
#include<stdio.h>
int main()
{
    /*array of strings*/
char arr[3][10]={
            "Ram",/*first string ie first char array*/
            "Bhagwan",
            "Yeshu"
            };
/*pointer to array.Each array is 1-d array of chars ie each array is string*/
char (*p)[10];
p=(char *)arr;/*  p=arr+0 so p first points to first char array ie first string Ram*/

char* pp;

How to use Pointer to An Array of Integers in C

What is Pointer to an Array in C?
int (*p)[4];//p is pointer to array and each array is having 4 its
 so,p points to base address of first array ie address of other elements of first array.
 p+1 points to base address of second array and not the 1st element of first array.
 p+2 points to base address of third array  and not the 2nd element of first array.
 To access the individual elements of each array:
 assign the pointer to array to a pointer to int here pp and access through *(pp+i).

#include<stdio.h>
int main()
{
    /*array of strings*/
    int arr[3][4]={
        {0,1,2,3},/*first string ie first char array*/
        {4,5,6,7},
        {8,9,1,2},
    };
    /*pointer to array.Each array is 1-d array of chars ie each array is string*/
    int (*p)[4];
    p=(int *)arr;/*  p=arr+0 so p first points to first char array ie first string Ram*/

    int* pp;

Pointer to use Array of Integers in C

How to use pointer to an array of integers:
 int a[]={10,20,30};//array of ints
 int (*p)[3];//p is pointer to array
 so if int *q=p then
 q points to first array {10,20,30}
 q+1 points to second array {garbage here}
 q+2 points to third array {garbage here}

Note:here only one 1-d array so using pointer to array is not useful.
So, generally pointer to array is used with multdimensional arrays

/*
 example of pointer to array, best with 2-d array as 2d array is array of multiple 1-d arrays

 int a2d[3][3]={//rray of three 1-d arrays each having 3 element
     {10,20,30},
     {40,50,60},
     {70,80,90}
 };
 int (*ptr)[3];//ptr is pointer to array of 3 ints so contins address
 ptr=a2d;
 */
 /*first row of 2d array is first 1-d array. ptr+0 contains the base address of first array{10,20,30}; */
 /*second row is second array ptr+2 contains the base address of second array{40,50,60};*/
 /*third row is third array ptr+2 contains the base address of third array{70,80,90};*/
/*
 so incremting ptr++ will give the base address of next array and not the next element of first array and so on
 so check how to access individual elements of array using pointer to array at last of code
 */
#include<stdio.h>
int main()
{
 int a[]={10,20,30};//array of ints
 int (*p)[3];/*p is pointer to array of 3 ints so contins address*/

 p=a;