1

我们如何访问结构的变量?我有一个结构:

typedef struct {
   unsigned short a;
   unsigned shout b;
} Display;

在我的另一堂课中,我有一个方法:

int NewMethod(Display **display)
{
   Display *disp=new Display();
   *display = disp;
   disp->a=11;
}

**显示是什么意思?要访问我使用过的 struct 变量->,还有其他方法吗?

4

6 回答 6

5

正如泰勒所说,双星号是“指向指针的指针”,您可以根据需要拥有任意多个级别的指针。

我相信您知道,箭头运算符 ( a->b) 是取消引用指针的星号和访问字段的点的快捷方式,即

a->b = (*a).b;

括号是必要的,因为点绑定得更紧密。双星号没有这样的运算符,在访问字段之前,您必须首先取消引用以达到所需的级别:

Display **dpl = ...;

(*dpl)->a = 42;

或者

(**dpl).a = 42;
于 2009-09-03T06:43:41.330 回答
2

将其视为*(*display). 当您想将整数的地址传递给函数以便设置整数时,您可以使用:

void setTo7 (int *x) {
    *x = 7;
}
: : :
int a = 4;
setTo7 (&a);
// a is now 7.

它与您所拥有的没有什么不同,只是您要设置指针的值,因此您需要将指针传递给该指针。很简单,不是吗?

试试这个:

#include <stdio.h>
#include <string.h>

static void setTo7 (int *x) { *x = 7; }

void appendToStr (char **str, char *app) {
    // Allocate enough space for bigger string and NUL.

    char *newstr = malloc (strlen(*str) + strlen (app) + 1);

    // Only copy/append if malloc worked.

    if (newstr != 0) {
        strcpy (newstr, *str);
        strcat (newstr, app);
    }

    // Free old string.

    free (*str);

    // Set string to new string with the magic of double pointers.

    *str = newstr;
}

int main (void) {
    int i = 2;
    char *s = malloc(6); strcpy (s, "Hello");
    setTo7 (&i); appendToStr (&s, ", world");
    printf ("%d [%s]\n",i,s);
    return 0;
}

输出是:

7 [Hello, world]

这将安全地将一个字符串值附加到另一个,分配足够的空间。双指针通常用于智能内存分配函数,在 C++ 中较少使用,因为您有一个原生字符串类型,但它对于其他指针仍然有用。

于 2009-09-03T06:50:01.317 回答
0

**display 只是一个双指针(指向 Display 类型指针的指针)。

于 2009-09-03T06:39:25.490 回答
0

**意味着它是一个指向指针的指针。基本上它指向另一个指针,然后指向其他东西,在你的情况下是一个Display结构。

如果您仅使用对象调用函数,则可以使用.运算符访问成员。

int NewMethod(Display display)
{
Display disp = display;
disp.a=11;
}

但是这样你不是直接修改Display display对象而是本地副本。您的代码表明需要在函数之外对对象进行更改,因此您唯一的选择是您描述的那个(好吧,也许通过引用传递参数,但语法或多或少相同(->))。

于 2009-09-03T06:43:31.987 回答
0

由于 disp 是一个指针,你必须使用 ->

如果您只有一个“正常”变量(即在堆栈上)显示 d;

你可以写达

结构与类相同。唯一的区别(我知道)是默认情况下所有成员都是公共的。

于 2009-09-03T06:43:54.527 回答
0

你可以做 (*disp).a=11;

它被称为取消引用

于 2009-09-03T06:49:31.723 回答