pointers, dynamic memo allocat for bidimensional arrays A sample
Well, here is a full sample that works but the console vanishes right after the last print and i cant make it stay. Also there are a few queries that I include in some lines
//bidimensional array dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
void main()
{
int **p; // pointer to pointer
int n,m,i,j,k; // n is rows, m is cols, i and j are the indexes of the array, k is going to be like m, but used to print out
do
{
printf("\n how many rows?");
scanf ("\%d", &n);
}
while (n <= 0);
// booking memory for an array of n elements, each element is a pointer to an int (int *)
//Query: a pointer to an int? wouldnt it be a pointer to a pointer ? It uses **
p = (int **) malloc (n * sizeof(int *)); //
if(p == NULL)
{
printf("Insuficient memory space");
exit( -1);
}
for (i = 0; i < n; i++) // now lets tell each row how many cols it is going to have
{
printf("\n\nNumber of cols of the row%d :", i+1); // for each row it can be different
scanf("%d", &m); // tell how many cols
p[i] = (int*)malloc(m * sizeof(int)); // we allocate a number of bytes equal to datatype times the number of cols per row
/Query: I cant grasp the p[i] because if p was a pointer to a pointer, what is that array notation, i mean the square brackets/
if(p[i] == NULL)
{ printf("Insuficient memory space");
exit(-1);
}
for (j=0;j<m;j++)
{
printf("Element[%d][%d]:", i+1,j+1);
scanf("%d",&p[i][j]); // reading through array notation
}
printf("\n elements of row %d:\n", i+1);
for (k = 0; k < m; k++)
// printing out array elements through pointer notation
printf("%d ", *(*(p+i)+k));
}
// freeing up memory assigned for each row
for (i = 0; i < n; i++)
free(p[i]);
free(p);// freeing up memory for the pointers matrix
getchar(); // it cannot stop the console from vanishing
fflush(stdin); // neither do开发者_JAVA技巧es this
}
// ********thanks a lot******
it's easy to understand pointers in context of arrays. So if
int * pis the one-dimensional array of int, then int ** p will be two -dimensional array of int. In other words it is an array that containt a pointers to one-dimensional array.
so
p = (int **) malloc (n * sizeof(int *)); //is a pointer to the pointer
and p[i] is current pointer to the int.
精彩评论