Pointers and Memory
Pointers and Memory
float x;
float *px;
x = 6.5;
px = &x;
#include<stdio.h> #include<stdio.h>
main () main ()
{ {
int a[5], x, y, i; int i,n, *pa;
printf("Input the value of N\n");
scanf("%d", &n);
printf("Input 5 values\n"); pa=malloc(n);
for(i=0;i<5;i++)
{ scanf("%d",&a[i]); }; printf("Input %d values\n", n);
for(i=0;i<n;i++)
printf("Print array with normal { scanf("%d", (pa+i)); };
and pointer methods\n");
for(i=0;i<5;i++) printf("\nprint array using dynamic
{ printf(“%d %d\n",a[i], pointer\n");
*(a+i)); }; for(i=0;i<n;i++)
} { printf(“%d\n", *(pa+i)); };
}
Multidimensional arrays and pointers
• A 2D (two dimensional) array (in maths similar to
matrix) is really a 1D array, each of whose
elements is itself an array.
• Hence in a[n][m] notation, there are n rows and
m columns.
• Array elements are stored row by row.
• When we pass a 2D array to a function we must
specify the number of columns and the number
of rows is irrelevant.
• The reason for this is pointers again. C needs to
know how many columns in order that it can
jump from row to row in memory.
Example:
• Consider int a[5][35] to be passed in a function:
• We can define function definition as:
f(int a[][35])
{ }
OR
f(int (*a)[35])
{ }