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:

 #include <stdio.h>

 int main()
{
int nrows=;  
int ncols=;
int row;
int **rowptr;
rowptr=malloc(nrows*sizeof(int *)); //分配5行(int *)型一维数组大小的空间
if (NULL==rowptr)
{
puts("\nFailure to allocate room for row pointers.\n");
exit();
}
printf("the address of rowptr is %p\n",rowptr);
printf("\nIndex Pointer(hex) Pointer(dec) Diff.(dec)");
for (row=;row<nrows;row++)
{
rowptr[row]=malloc(ncols*sizeof(int)); //rowptr指针数组的每一个指针指向一块10个int型元素大小的内存
if (NULL==rowptr[row])
{
printf("\nFailure to allocate for row[%d]\n",row);
exit();
} printf("\n%d %p %d",row,rowptr[row],rowptr[row]);
if(row>)
printf(" %d",(rowptr[row]-rowptr[row-]));
}
puts("\n"); return ;
}

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:

 #include <stdio.h>

 int main()
{
int **rptr; //用来指向指针数组
int *aptr; //用来指向一个二维数组
int *testptr; //测试指针,证明二维数组是在一个连续的内存区域
int k;
int nrows=; //5行
int ncols=; //8列
int row,col; printf("we now allocate the memory for the array\n");
aptr=malloc(nrows*ncols*sizeof(int)); //分配5行8列整型二维数组大小的空间
printf("\nthe address of the array is %p\n",aptr); if (NULL==aptr) //反过来写是为了防止出错不易检查
{
puts("\nFailure to allocate room for the array");
exit();
} printf("\nwe now allocate room for the pointers to the rows\n");
rptr=malloc(nrows*sizeof(int *)); //分配5行(int *)型一维数组大小的空间
printf("\nthe address of the pointers to the rows is %p\n",rptr); if (NULL==rptr)
{
printf("\nFailure to allocate room for pointers");
exit();
} printf("\nnow we 'point' the pointers:\n");
for (k=;k<nrows;k++)
{
rptr[k]=aptr+(k*ncols); //为指针数组的每一个元素赋一个地址(存储的地址为二维数组每行的首地址)
printf("the pointer address of the rptr[%d] is %p\n",k,rptr[k]);
}
printf("\nNow we illustrate how the row pointers are incremented\n");
printf("Index Pointer(hex) Diff.(dec)"); for (row=;row<nrows;row++)
{
printf("\n%d %p",row,rptr[row]); //以十六进制打印出指针数组中存储的地址
if(row>)
printf(" %d",(rptr[row]-rptr[row-])); //①
} printf("\n\nAnd now we print out the array\n");
for (row=;row<nrows;row++)
{
for(col=;col<ncols;col++)
{
*(*(rptr+row)+col)=row+col; //移动指针数组中的指针,使其指向分配的内存块中的每一个地址,并赋值
printf("%d ",rptr[row][col]);
}
printf("\n");
} puts("\n"); printf("And now we demonstrate that they are contiguous in memory\n");
testptr=aptr; //指向二维数组首地址
for (row=;row<nrows;row++)
{
for (col=;col<ncols;col++)
{
//将以上指针在一块连续的内存中每次移动一个地址,打印其值,结果如与以上结果吻合,说明二维数组所在的内存区域是一块连续内存
printf("%d ",*(testptr++));
}
putchar('\n');
} return ;
}

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位,而是之间相隔的元素的个数。

再看一个示例:

 #include <stdio.h>
#define N 8
int main()
{
int str[N]={,,,,,,,};
int *p;
p=str;
printf("&p[0]=%p\n&p[4]=%p\n",p,&p[]);
printf("p[4]-p[0]=%d\n",(p+)-&p[]); return ;
}

结果:

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:

 #include <stdio.h>
#include <stddef.h> int X_DIM=;
int Y_DIM=;
int Z_DIM=; int main()
{
char *space;
char ***Arr3D;
int y,z;
ptrdiff_t diff;
/*first we set aside space for the array itself*/ space=malloc(X_DIM*Y_DIM*Z_DIM*sizeof(char)); printf("the address of space is %p\n",space); /*next we allocate space of an array of pointers,each
to eventually point to first element of a
2 dimensional array of pointers to pointers*/ Arr3D=malloc(Z_DIM*sizeof(char **));
printf("the address of Arr3D is %p\n",Arr3D); /*and for each of these we assign a pointer to a newly
allocated array of pointers to a row*/ for (z=;z<Z_DIM;z++)
{
Arr3D[z]=malloc(Y_DIM*sizeof(char *)); /*and for each space in this array we put a pointer to
the first element of each row in the array space
originally allocated */ for (y=;y<Y_DIM;y++)
{
Arr3D[z][y]=space+(z*(X_DIM*Y_DIM)+y*X_DIM);
}
}
/*And, now we check each address in our 3D array to see if
the indexing of the Arr3D pointer leads through in a
continuous manner*/ for (z=;z<Z_DIM;z++)
{
printf("Location of array %d is %p\n",z,*Arr3D[z]);
for (y=;y<Y_DIM;y++)
{
printf("Array %d and Row %d starts at %p",z,y,Arr3D[z][y]);
diff=Arr3D[z][y]-space;
printf(" diff=[%d] ",diff);
printf(" z=%d y=%d\n",z,y);
}
}
return ;
}

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.

Pointers and Dynamic Allocation of Memory的更多相关文章

  1. c++: Does the new operator for dynamic allocation check for memory safety?

    Quesion: My question arises from one of my c++ exercises (from Programming Abstraction in C++, 2012 ...

  2. Safe and efficient allocation of memory

    Aspects of the present invention are directed at centrally managing the allocation of memory to exec ...

  3. Method for training dynamic random access memory (DRAM) controller timing delays

    Timing delays in a double data rate (DDR) dynamic random access memory (DRAM) controller (114, 116) ...

  4. PatentTips - Method to manage memory in a platform with virtual machines

    BACKGROUND INFORMATION Various mechanisms exist for managing memory in a virtual machine environment ...

  5. Google C++ Style Guide

    Background C++ is one of the main development languages used by many of Google's open-source project ...

  6. Google C++ 代码规范

    Google C++ Style Guide   Table of Contents Header Files Self-contained Headers The #define Guard For ...

  7. Poly

    folly/Poly.h Poly is a class template that makes it relatively easy to define a type-erasing polymor ...

  8. Linux I/O scheduler for solid-state drives

    An I/O scheduler and a method for scheduling I/O requests to a solid-state drive (SSD) is disclosed. ...

  9. Memory Allocation with COBOL

    Generally, the use of a table/array (Static Memory) is most common in COBOL modules in an applicatio ...

随机推荐

  1. linux一些目录功能

    (1)/etc     ----存放配置文件和子目录 (2)/dev     -----是linux的外设文件,dev是devxe(设备)的缩写,在这个目录下存放的是所有linux的外设文件,.在li ...

  2. a标签中href的触发

    采用.trigger('click')没有效果,是用的$('xx')[0].click()来触发的.不知道为什么trigger不行,望指导.

  3. Android菜鸟成长记8 -- 布局实践(微信界面的编写)

    前面我们简单的介绍了一下android的五大布局,那么现在我们来实践一下,写一个简单的微信界面 首先,我们新建一个weixin.xml的linnerlayout布局 我们日常使用的微信,从简单的方面来 ...

  4. 你不知道的this指向

    javascript中,我们预想的this指向,有时候与预期不一样,直接上经典例子 window.name=2; var test={ 'name':1, 'getName':function(){ ...

  5. DDR控制

    先看下micron公司对DDR3命名的规则: 在设置xilinx ISE中的DDR时 在选择芯片时,不清楚该怎么选择. 请教汤工,给出的答案是Speed等级高的可以兼容等级低的芯片,个在实验之中用的是 ...

  6. C#窗体技巧

    //限制文本框只能输入数字且允许按退格键删除数字,其它键盘输入不予显示private void 文本框名_KeyPress(object sender, KeyPressEventArgs e)  { ...

  7. flask文件的上传和下载

    from werkzeug.utils import secure_filename from flask import Flask,render_template,jsonify,request i ...

  8. 初涉定制linux系统之——自动化安装Centos系统镜像制作

    最近碰到个需求:要在内网环境安装centos6.5系统并搭建服务,但由于自动部署脚本里安装依赖包使用的是yum安装,而服务器无法连接外网,实施人员也不会本地yum源搭建O__O "….. 本 ...

  9. url 处理

    一.jsp异步请求后台(servlet) 的url RegisterServlet  与 web.xml 的路径一样 function checkPhoneNumber(){ var phonenum ...

  10. 自定义View的学习(一) 自绘制控件

    一.自绘控件 就是自己绘制的控件,通过onDraw()方法将控件绘制出来  自定义一个可点击的View  这个View可以记住用户点击的次数 public class CounterView exte ...