Docsity

Pointer Part 2-Computer Fundamentals-Lab Codes, Exercises of Computer Fundamentals

Toggle sidebar
bg1
#include <stdio.h>
#include <stdlib.h>
/* prototype of function print that accept a pointer to pointer (in other
words
* 2D array
*/
void print(int **ar, int r, int c);
int main()
{
int r=3,c=5,i,j;
// int a1[2][4]={{1,2,3,4},{5,6,7,8}};
int **aptr; // pointer to pointer
// initializing arrays of pointer of size r
aptr=(int*)malloc(r*sizeof(int*));
for(i=0;i<r;i++)
{
aptr[i]=(int)malloc(c*sizeof(int));
// initializing each pointer with array size of c of interger
}
printf("Done with initializing \n\n\n");
for (i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
aptr[i][j]=rand()%20;
}
}
printf("Done with initialization Value \n\n\n");
for (i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf( "aptr[ %d ][ %d ] = %d\n",i ,j,aptr[i][j] );
}
}
printf("Going in to function \n\n\n");
print(aptr,r,c);
printf("Coming out of function \n\n\n");
/*
* Should free memory at the end of the program or when no more
required
*/
for(i=0;i<r;i++)
{
free(aptr[i]);
}
free(aptr);
docsity.com
pf2

Partial preview of the text

Download Pointer Part 2-Computer Fundamentals-Lab Codes and more Exercises Computer Fundamentals in PDF only on Docsity!

#include <stdio.h> #include <stdlib.h>

/* prototype of function print that accept a pointer to pointer (in other words

  • 2D array */ void print(int **ar, int r, int c);

int main() { int r=3,c=5,i,j; // int a1[2][4]={{1,2,3,4},{5,6,7,8}}; int **aptr; // pointer to pointer

// initializing arrays of pointer of size r aptr=(int)malloc(rsizeof(int)); for(i=0;i<r;i++) { aptr[i]=(int)malloc(csizeof(int)); // initializing each pointer with array size of c of interger } printf("Done with initializing \n\n\n"); for (i=0;i<r;i++) { for(j=0;j<c;j++) { aptr[i][j]=rand()%20; } } printf("Done with initialization Value \n\n\n");

for (i=0;i<r;i++) { for(j=0;j<c;j++) { printf( "aptr[ %d ][ %d ] = %d\n",i ,j,aptr[i][j] ); } } printf("Going in to function \n\n\n"); print(aptr,r,c); printf("Coming out of function \n\n\n");

/*

  • Should free memory at the end of the program or when no more required */ for(i=0;i<r;i++) { free(aptr[i]); } free(aptr);

docsity.com

return 0; }

/* Definition of function print that accept a pointer to pointer (in other words

  • 2D array */ void print(int **ar, int r, int c) { int i,j; for (i=0;i<r;i++) { for(j=0;j<c;j++) { // pointer to pointer in context of arrays is treated similarly as // 2 D array and we can use subscript printf( "Array subscript ar[ %d ][ %d ] = %d \t ",i ,j,ar[i][j] );

// there is a bit difference from what we do before. printf( "Pointer dereference ar = %d \n",(((ar+i))+j));

} } }

docsity.com