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. Windows服务二:测试新建的服务、调试Windows服务

    一.测试Windows服务 为了使Windows服务程序能够正常运行,我们需要像创建一般应用程序那样为它创建一个程序的入口点.像其他应用程序一样,Windows服务也是在Program.cs的Main ...

  2. Android(Logcat、Monitors)

    刚学习Android 的时候总喜欢输出"Hello Word"这样的信息来判断是不是执行了某个方法,最初连Android Studio控制台.断点这些在哪里都要找好久,现在好了多点 ...

  3. linux配置java环境变量(详细)

    linux配置java环境变量(详细) 本文完全引用自: http://www.cnblogs.com/samcn/archive/2011/03/16/1986248.html 一. 解压安装jdk ...

  4. windows与linux之间文件的传输方式总结(转)

    当然,windows与linux之间文件的传输的两种方式有很多,这里就仅仅列出工作中遇到的,作为笔记: 方法一:安装SSH Secure Shell Client客户端 安装即可登录直接拖拉到linu ...

  5. lua和整合实践

    这几天研究了一下lua,主要关注的是lua和vc之间的整合,把代码都写好放在VC宿主程序里,然后在lua里调用宿主程序的这些代码(或者叫接口.组件,随便你怎么叫),希望能用脚本来控制主程序的行为.这实 ...

  6. RandomAccessFile拆分合并文件

    import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java. ...

  7. ZT 螨虫知识2

    病情分析:过敏是治不好的,只能做到避免接触.指导意见:螨虫的话就不要跟狗多接触,狗的寄生虫很多,还有草地,尤其是狗经常去的地方,草地就是螨虫的传播介质.你是过敏性体质除了被免过敏性源外,还要增强体质, ...

  8. 网络-->监控-->单位换算

    The metric system In some cases when used to describe data transfer rates bits/bytes are calculated ...

  9. 提高SQL查询效率(SQL优化)

    要提高SQL查询效率where语句条件的先后次序应如何写 http://blog.csdn.net/sforiz/article/details/5345359   我们要做到不但会写SQL,还要做到 ...

  10. 如何去掉Eclipse里面自动追加的一些注释!!!内详

    比如我创建一个类,勾选了自动生成main函数.他就来一个// TODO Auto-generated method stub比如我输入"try"然后自动补完try catch bl ...