gpt4 book ai didi

c - 在 C 中使用 calloc 时,指针地址中存储的是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:44 25 4
gpt4 key购买 nike

我很难理解这个程序来说明指针(来自 http://theocacao.com/document.page/234 ):

下面我不明白为什么:

int * currentSlot = memoryBlock

没有使用&memoryBlock。我读了评论,但不明白。什么是 memoryBlock 放在那里而 &memoryBlock 不会?不会都返回指向用 calloc 创建的整数集的指针(假设我了解已经完成的工作)? calloc 之后的* memoryBlock 中到底是什么?

然后在这里,*currentSlot = rand();,这里的解引用是如何工作的?我认为取消引用会阻止 *currentSlot 将内存地址(引用)的值赋予实际值(不再是引用而是值)。

#include <stdio.h>
#include <stdlib.h> // for calloc and free
#include <time.h> // for random seeding

main ()
{
const int count = 10;
int * memoryBlock = calloc ( count, sizeof(int) );

if ( memoryBlock == NULL )
{
// we can't assume the memoryBlock pointer is valid.
// if it's NULL, something's wrong and we just exit
return 1;
}

// currentSlot will hold the current "slot" in the,
// array allowing us to move forward without losing
// track of the beginning. Yes, C arrays are primitive
//
// Note we don't have to do '&memoryBlock' because
// we don't want a pointer to a pointer. All we
// want is a _copy_ of the same memory address

int * currentSlot = memoryBlock;


// seed random number so we can generate values
srand(time(NULL));

int i;
for ( i = 0; i < count; i++ )
{
// use the star to set the value at the slot,
// then advance the pointer to the next slot
*currentSlot = rand();
currentSlot++;
}

// reset the pointer back to the beginning of the
// memory block (slot 0)
currentSlot = memoryBlock;

for ( i = 0; i < count; i++ )
{
// use the star to get the value at this slot,
// then advance the pointer
printf("Value at slot %i: %i\n", i, *currentSlot);
currentSlot++;
}

// we're all done with this memory block so we
// can free it
free( memoryBlock );
}

感谢您的帮助。

最佳答案

Below I don't understand why:

int * currentSlot = memoryBlock

isn't using &memoryBlock.

因为memoryBlockcurrentSlot都是指向int的指针。 &memoryBlock 将是指向 int 的指针的地址,即 int **

“在”memoryBlock 中的是指向内存块的指针。

Then here, *currentSlot = rand();, how does the dereferencing work here?

这是 C 的规则:当像这样的解引用表达式出现在表达式的左侧时,右侧的值存储在被解引用的指针指向的内存位置。

关于c - 在 C 中使用 calloc 时,指针地址中存储的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8436254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com