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. Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版

    Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...

  2. Java垃圾回收机制 入门

    对于Java虚拟机的了解,我认为是一个Java程序员已经入门的重要标志,而JVM中的垃圾回收机制(Garbage Collection,简称GC)又是JVM中的重点,所以hans在这里用篇文章时间和大 ...

  3. tcl学习

    variables(变量) 语法:set varname value 例如:set a 5 注意:大小写敏感,任意长度,任意字符 使用之前无需申明 substitution(替换) 1 变量值替换 $ ...

  4. Git相关知识

    一些有用的链接: https://www.git-scm.com/ http://nvie.com/posts/a-successful-git-branching-model/ Git开发模式: 建 ...

  5. Webstorm官方最新版本for Mac版本 不用注册码/破坏原文件

    首先,说明下我自己安装的时候看到网上无外乎两种方法: 下载别人封装好的安装包,把JetbrainsCrack.jar复制到/Applications/WebStorm.app/Contents/bin ...

  6. java的Map及Map.Entry解析

    Map<K,V>是以键-值对存储的(key-value), 而Entry<K,V>是Map中的一个接口,Map.Entry<K,V>接口主要用于获取.比较 key和 ...

  7. mysql中的SUBSTRING_INDEX

    SUBSTRING_INDEX(str,delim,count) Returns the substring from string str before count occurrences of t ...

  8. 查看Windows服务器登录日志

    本文以Windows7系统为例:[控制面板]——[管理工具]——[查看事件日志]——[Windows日志]——[安全].此时在视图窗口应该可以看到登录信息了,如果需要知道具体信息那么可以点击某条记录或 ...

  9. Eclipse之Git提交项目

    一.使用eclipse自带插件提交项目 1.自带git插件进行配置我们的用户名和密码,即是自己github注册的用户. windows-perferences-Team-Git-configurati ...

  10. 【译】RabbitMQ:Topics

    在前面的教程中,我们对日志系统进行了功能强化.我们使用direct类型的交换器并且为之提供了可以选择接收日志的能力,替换了只能傻乎乎的广播消息的fanout类型的交换器.尽管使用direct类型的交换 ...