java - 当您需要创建一个指向变量的指针时,为什么指针可以节省内存?

标签 java python c++ c pointers

我理解指针是用来指向变量的内存地址的。如果我错了请纠正我,指针不是也有自己的内存地址吗?您基本上不是创建另一个具有相同值的变量吗?

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/

相关文章:

c++ - 从函数返回多个 auto_ptr

java - 如何在 firestore 中点击 URL 时在 firebase 存储上上传 2 张图像

java - 等待性,轮询直到满足条件

python - 无法捆绑 OpenCV 和 PyQt5

python - 获取相关对象列表 - Django Queryset

Python:忽略后台进程中的信号

java - 毫秒未出现在 DateFormat.format 输出中

java.sql.SQLRecoverableException : The Network Adapter could not establish the connection

c++ - 显示功能状态的 QT 进度条

c++ - Qt double spin box 在处理值改变时自动填充