【问题标题】:Why do pointers save memory when you need to create a pointer to point to a variable? [closed]为什么需要创建指向变量的指针时,指针会节省内存? [关闭]
【发布时间】:2016-08-21 00:22:14
【问题描述】:

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

int example = 10; // VALUE of example is 10
int *pointer = &example; // pointer is equal to the memory ADDRESS of example

指针不是也有它自己的内存地址吗? 指针如何更有效,什么时候指针真正有用的例子是什么?非常感谢。

【问题讨论】:

  • 等等,python真的有指针吗?无论如何,您标记了 4 种不同的编程语言,每种语言都有自己的指针用途(如果有的话)。你应该选择一个。另外,定义“高效”:在什么意义上,与什么相比?
  • 为什么你认为指针的目的是节省内存?
  • 好的,我会确保下次我做的不一样。我的意思是,指针如何提高内存效率。

标签: java python c++ c pointers


【解决方案1】:

是的,指针有自己的内存地址,占用了一些空间。

但是,如果您可以在说六个对象或一个对象和五个指向它的指针之间进行选择,您认为哪个更有效?

这是一个例子:

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);
}

【讨论】:

  • 您忘记解决问题的 python、java 和 C++ 部分。 ://
  • 不,我没有忘记。问题涉及指针,适用于所有语言。
  • 感谢您的回答
  • 哎呀,对不起,我没有意识到 python 不使用指针,我刚刚开始。
  • @Scottytwotime Java 也没有
【解决方案2】:

指针在指向大块数据或大结构时效率更高。如果您传递的地址通常是 4 或 8 字节,那么这只是堆栈上的一个微不足道的副本,而不是兆字节或千兆字节的潜在数据。

确实,指针实际上可以比它指向的值包含更多的数据。例如:

int x = 1;
int *y = &x;

在 64 位系统上,y 实际上是 8 个字节,指向的数据只有 4 个字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2010-10-28
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多