我的理解是,
下面是一个创建字符串数组的函数:
在我的系统上(Win7,32位编译,ANSI C),这行代码是:
这导致以下结果:
这表明指针
有人能解释一下在
malloc()/calloc()
分配内存时创建的对象一旦被创建,其地址将保持不变。但我经常使用的一个函数用于创建字符串数组,一直以来都表现良好,最近让我对自己的理解产生了质疑,也就是说,仅仅调用 calloc/malloc
函数,对象的内存地址是可以被移动的(而且确实被移动了)。下面是一个创建字符串数组的函数:
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,32位编译,ANSI C),这行代码是:
a = calloc(numWords, sizeof(char *)); //create array of pointers
创建一个连续的内存块,大小为numWordschar *
,在这种情况下为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
}
这导致以下结果:
![enter image description here](https://istack.dev59.com/mjglo.webp)
这表明指针
a[1] - a[6]
的内存位置已被更改。有人能解释一下在
malloc()/calloc()
中为什么会发生这种情况吗?
a
是从函数中返回的。 - Hogan