我理解指针是用来指向变量的内存地址的。如果我错了请纠正我,指针不是也有自己的内存地址吗?您基本上不是创建另一个具有相同值的变量吗?
int example = 10; // VALUE of example is 10
int *pointer = &example; // pointer is equal to the memory ADDRESS of example
指针不是也有自己的内存地址吗? 指针如何更有效?指针何时真正有用的示例是什么?非常感谢。
最佳答案
是的,指针有自己的内存地址并占用一些空间。
但是,如果您可以在六个对象或一个对象和五个指向它的指针之间进行选择,您认为哪个更有效?
这是一个例子:
struct bigStruct
{
char message[1024];
};
void printBigStructDirectly(struct bigStruct s)
{
// When you call this, the computer makes a copy of bigStruct.
// Now both "s", and "bs" in the caller, take up 1024 bytes each,
// so 2048 bytes total.
printf("%s\n", s.message);
}
void printBigStructWithPointer(struct bigStruct *ps)
{
// When you call this, the computer only makes a pointer variable.
// Now "bs" in the caller takes up 1024 bytes, and "ps" here
// takes 4 or 8 bytes, so 1028 or 1032 bytes total.
printf("%s\n", ps->message);
}
void test(void)
{
struct bigStruct bs;
strcpy(bs.message, "Hello world!");
printBigStructDirectly(bs);
printBigStructWithPointer(&bs);
}
关于java - 当您需要创建一个指向变量的指针时,为什么指针可以节省内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36877358/