大佬教程收集整理的这篇文章主要介绍了使用malloc()/ calloc()创建内存的错误概念,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
为了说明,这里是我用来为字符串数组创建内存的函数 – char **:
char ** CreateArrayOfStrings(char **a,int numWords,int maxWordLen) { int i; a = calloc(numWords,sizeof(char *)); //create array of pointers if(!a) return a; //required caller to check for NULL for(i=0;i<numWords;i++) { a[i] = calloc(maxWordLen + 1,1); //create memory for each String } return a; }
在我的系统上,(Win7,32bit编译,ANSI C)该行:
a = calloc(numWords,sizeof(char *)); //create array of pointers
创建一个连续内存块,大小为numWords char *,在本例中为7,产生28个字节:
内存跨度从地址0x03260080 1C(0x0326009C)
要么:
a[0] is at 0x3200260080 a[1] is at 0x3200260084 a[2] is at 0x3200260088 a[3] is at 0x320026008C a[4] is at 0x3200260090 a[5] is at 0x3200260094 a[6] is at 0x3200260098
然后,我为每个numWords(7)字符串创建内存
for(i=0;i<numWords;i++) { a[i] = calloc(maxWordLen + 1,1); //maxWordLen == 5 in this example }
其结果如下:
这表明指针a [1] – a [6]的存储位置已经改变.
有人可以解释在malloc()/ calloc()中如何/为什么会这样?
以上是大佬教程为你收集整理的使用malloc()/ calloc()创建内存的错误概念全部内容,希望文章能够帮你解决使用malloc()/ calloc()创建内存的错误概念所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。