如何访问嵌套结构中的指针

How to access pointer within a nested structure

假设我在 C 编程语言中有这样的代码

typedef struct up {
    char *str;
} up;

typedef struct up_cont{
    up at;
}up_cont;

我已经定义了up_cont real;。我已经完成所有分配和所有!

现在我想将 "Hello" 存储在字符串中。我在努力

 up_cont real;
*(real.at.str) = "Hello";

它不起作用!!

并请建议如何打印!!

假设您的 typedef 如下所示

typedef struct up_cont{
    up at;
}up_cont;

(我认为上面的代码片段有更多的错字)


你的问题的答案是,str 本身就是一个指针。只需使用

 real.at.str = "Hello";

编辑:

And please also suggest how to print it!!

只是您打印任何其他 字符串 的正常方式。使用

 printf("str contains %s\n", real.at.str);

您可以阅读更多关于 printf() here


脚注:

FWIW,如果您使用将字符串文字分配给指针,它将是只读的,您不能更改内容。如果你想要一个可修改的字符串,你需要
1。使用 malloc() 或 family
动态分配内存 2。使用strcpy()字符串文字复制到分配的内存

typedef struct up_cont{
    up at;
};

在 C 语言中,您没有在此处键入任何内容。 你的意思是:

typedef struct up_cont{
    up at;
} up_cont;

然后像这样访问它:

up_cont *p = /* ... */;
p->at.str = "hello";

正如其他人提到的那样,在 C++ 中,您的结构中需要一个 const char * 成员来具有指向字符串文字的指针(char * 在 C 中是可以的)。

访问嵌套结构成员的语法如您所见:real.at.str.

无效的是您取消引用 real.at.str。作业

  real.at.str = "Hello";

将起作用,方法是将左侧指定为字符串文字中第一个字符的地址。

请记住,修改字符串会产生未定义的行为

  real.at.str[0] = 'B';

因为它试图用字符 'B'.

覆盖字符串文字 "Hello" (实际上是编译时间常量)的第一个字符