Pointers and Dynamic Allocation of Memory
METHOD 1:
Consider the case where we do not know the number of elements in each row at compile time, i.e. both the number of rows and number of columns must be determined at run time. One way of doing this would be to create an array of pointers to type int and then allocate space for each row and point these pointers at each row. Consider:
1 #include <stdio.h> 2 3 int main() 4 { 5 int nrows=5; 6 int ncols=10; 7 int row; 8 int **rowptr; 9 rowptr=malloc(nrows*sizeof(int *)); //分配5行(int *)型一维数组大小的空间 10 if (NULL==rowptr) 11 { 12 puts("\nFailure to allocate room for row pointers.\n"); 13 exit(0); 14 } 15 printf("the address of rowptr is %p\n",rowptr); 16 printf("\nIndex Pointer(hex) Pointer(dec) Diff.(dec)"); 17 for (row=0;row<nrows;row++) 18 { 19 rowptr[row]=malloc(ncols*sizeof(int)); //rowptr指针数组的每一个指针指向一块10个int型元素大小的内存 20 if (NULL==rowptr[row]) 21 { 22 printf("\nFailure to allocate for row[%d]\n",row); 23 exit(0); 24 } 25 26 printf("\n%d %p %d",row,rowptr[row],rowptr[row]); 27 if(row>0) 28 printf(" %d",(rowptr[row]-rowptr[row-1])); 29 } 30 puts("\n"); 31 32 return 0; 33 }
The result:
In the above code rowptr is a pointer to pointer to type int. In this case it points to the first element of an array of pointers to type int. Consider the number of calls to malloc():
To get the array of pointers 1 call
To get space for the rows 5 calls
-----
Total 6 calls
If you choose to use this approach note that while you can use the array notation(符号) to access individual elements of the array, e.g. rowptr[row][col] = 17;, it does not mean that the data in the "two dimensional array" is contiguous in memory.
If you want to have a contiguous block of memory dedicated to the storage of the elements in the array you can do it as follows:
METHOD 2:
In this method we allocate a block of memory to hold the whole array first. We then create an array of pointers to point to each row. Thus even though the array of pointers is being used, the actual array in memory is contiguous. The code looks like this:
1 #include <stdio.h> 2 3 int main() 4 { 5 int **rptr; //用来指向指针数组 6 int *aptr; //用来指向一个二维数组 7 int *testptr; //测试指针,证明二维数组是在一个连续的内存区域 8 int k; 9 int nrows=5; //5行 10 int ncols=8; //8列 11 int row,col; 12 13 printf("we now allocate the memory for the array\n"); 14 aptr=malloc(nrows*ncols*sizeof(int)); //分配5行8列整型二维数组大小的空间 15 printf("\nthe address of the array is %p\n",aptr); 16 17 if (NULL==aptr) //反过来写是为了防止出错不易检查 18 { 19 puts("\nFailure to allocate room for the array"); 20 exit(0); 21 } 22 23 printf("\nwe now allocate room for the pointers to the rows\n"); 24 rptr=malloc(nrows*sizeof(int *)); //分配5行(int *)型一维数组大小的空间 25 printf("\nthe address of the pointers to the rows is %p\n",rptr); 26 27 28 if (NULL==rptr) 29 { 30 printf("\nFailure to allocate room for pointers"); 31 exit(0); 32 } 33 34 printf("\nnow we 'point' the pointers:\n"); 35 for (k=0;k<nrows;k++) 36 { 37 rptr[k]=aptr+(k*ncols); //为指针数组的每一个元素赋一个地址(存储的地址为二维数组每行的首地址) 38 printf("the pointer address of the rptr[%d] is %p\n",k,rptr[k]); 39 } 40 printf("\nNow we illustrate how the row pointers are incremented\n"); 41 printf("Index Pointer(hex) Diff.(dec)"); 42 43 for (row=0;row<nrows;row++) 44 { 45 printf("\n%d %p",row,rptr[row]); //以十六进制打印出指针数组中存储的地址 46 if(row>0) 47 printf(" %d",(rptr[row]-rptr[row-1])); //① 48 } 49 50 printf("\n\nAnd now we print out the array\n"); 51 for (row=0;row<nrows;row++) 52 { 53 for(col=0;col<ncols;col++) 54 { 55 *(*(rptr+row)+col)=row+col; //移动指针数组中的指针,使其指向分配的内存块中的每一个地址,并赋值 56 printf("%d ",rptr[row][col]); 57 } 58 printf("\n"); 59 } 60 61 puts("\n"); 62 63 printf("And now we demonstrate that they are contiguous in memory\n"); 64 testptr=aptr; //指向二维数组首地址 65 for (row=0;row<nrows;row++) 66 { 67 for (col=0;col<ncols;col++) 68 { 69 //将以上指针在一块连续的内存中每次移动一个地址,打印其值,结果如与以上结果吻合,说明二维数组所在的内存区域是一块连续内存 70 printf("%d ",*(testptr++)); 71 } 72 putchar('\n'); 73 } 74 75 return 0; 76 }
The result:
Consider again, the number of calls to malloc()
To get room for the array itself 1 call
To get room for the array of ptrs 1 call
----
Total 2 calls
Now, each call to malloc() creates additional space overhead since malloc() is generally implemented(执行) by the operating system forming a linked list which contains data concerning the size of the block. But, more importantly, with large arrays (several hundred rows) keeping track of(跟踪) what needs to be freed when the time comes can be more cumbersome(麻烦的). This, combined with the contiguousness (邻接)of the data block that permits initialization to all zeroes using memset() would seem to make the second alternative the preferred one.
注:Diff.(dec)输出结果均为8,而不是十进制数32,为什么?
想想看,8刚好是每行的元素个数,也就是说指针(地址)相减不是地址值的差8*4=32位,而是之间相隔的元素的个数。
再看一个示例:
1 #include <stdio.h> 2 #define N 8 3 int main() 4 { 5 int str[N]={1,2,3,4,5,6,7,8}; 6 int *p; 7 p=str; 8 printf("&p[0]=%p\n&p[4]=%p\n",p,&p[4]); 9 printf("p[4]-p[0]=%d\n",(p+4)-&p[0]); 10 11 return 0; 12 }
结果:
As a final example on multidimensional(多维的) arrays we will illustrate the dynamic allocation of a three dimensional array. This example will illustrate one more thing to watch when doing this kind of allocation. For reasons cited above we will use the approach outlined(概括) in alternative two. Consider the following code:
1 #include <stdio.h> 2 #include <stddef.h> 3 4 int X_DIM=16; 5 int Y_DIM=5; 6 int Z_DIM=3; 7 8 int main() 9 { 10 char *space; 11 char ***Arr3D; 12 int y,z; 13 ptrdiff_t diff; 14 /*first we set aside space for the array itself*/ 15 16 space=malloc(X_DIM*Y_DIM*Z_DIM*sizeof(char)); 17 18 printf("the address of space is %p\n",space); 19 20 /*next we allocate space of an array of pointers,each 21 to eventually point to first element of a 22 2 dimensional array of pointers to pointers*/ 23 24 Arr3D=malloc(Z_DIM*sizeof(char **)); 25 printf("the address of Arr3D is %p\n",Arr3D); 26 27 /*and for each of these we assign a pointer to a newly 28 allocated array of pointers to a row*/ 29 30 for (z=0;z<Z_DIM;z++) 31 { 32 Arr3D[z]=malloc(Y_DIM*sizeof(char *)); 33 34 /*and for each space in this array we put a pointer to 35 the first element of each row in the array space 36 originally allocated */ 37 38 for (y=0;y<Y_DIM;y++) 39 { 40 Arr3D[z][y]=space+(z*(X_DIM*Y_DIM)+y*X_DIM); 41 } 42 } 43 /*And, now we check each address in our 3D array to see if 44 the indexing of the Arr3D pointer leads through in a 45 continuous manner*/ 46 47 for (z=0;z<Z_DIM;z++) 48 { 49 printf("Location of array %d is %p\n",z,*Arr3D[z]); 50 for (y=0;y<Y_DIM;y++) 51 { 52 printf("Array %d and Row %d starts at %p",z,y,Arr3D[z][y]); 53 diff=Arr3D[z][y]-space; 54 printf(" diff=[%d] ",diff); 55 printf(" z=%d y=%d\n",z,y); 56 } 57 } 58 return 0; 59 }
The result:
There are a couple of points that should be made however. Let's start with the line which reads:
Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
Note that here space is a character pointer, which is the same type as Arr3D[z][y]. It is important that when adding an integer, such as that obtained by evaluation of the expression (z*(X_DIM * Y_DIM) + y*X_DIM), to a pointer, the result is a new pointer value. And when assigning pointer values to pointer variables the data types of the value and variable must match.
posted on 2015-04-18 16:34 chunlanse2014 阅读(266) 评论(0) 编辑 收藏 举报