如何在没有“ - ”的情况下访问财产。在C中?

发布于 2025-01-30 11:37:47 字数 731 浏览 3 评论 0原文

我已经学习C了一段时间了,假设我以为我对指针有很好的了解,尽管这个例子让我感到困惑。

假设我们有一个数组,每个元素都指向一个结构。如果我们为两个元素分配空间,例如示例:


p = (test**)malloc(2*sizeof(test*));

p[0] = (test*)malloc(sizeof(test));
p[1] = (test*)malloc(sizeof(test));

这是结构测试:

typedef struct {
    char *t;
    long long p;
} test;

现在,当我将值分配给以下变量时:

(*p)[1].t = (char*)malloc(10*sizeof(char));
strcpy((*p)[1].t, "test");
(*p)[1].p = 10;

p[1]->t = (char*)malloc(10*sizeof(char));
p[1]->p = 20;
strcpy(p[1]->t, "test34e");

它们填充了完全不同的内存块。在此示例中,我如何能够访问属性t (*p)[1] .t

I've been learning c for a while, and let's say I thought I had a good understanding of pointers though this example is bugging me.

Let's say we have an array in which each element points to a structure. If we allocate space for two elements like in the example bellow:


p = (test**)malloc(2*sizeof(test*));

p[0] = (test*)malloc(sizeof(test));
p[1] = (test*)malloc(sizeof(test));

Here's the structure test:

typedef struct {
    char *t;
    long long p;
} test;

And now when I assign values to the variables like below:

(*p)[1].t = (char*)malloc(10*sizeof(char));
strcpy((*p)[1].t, "test");
(*p)[1].p = 10;

p[1]->t = (char*)malloc(10*sizeof(char));
p[1]->p = 20;
strcpy(p[1]->t, "test34e");

They fill completely different chunks of memory. How am I able to access property t at all in this example (*p)[1].t?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

智商已欠费 2025-02-06 11:37:47

看来您的意思

(*p[1] ).t = (char*)malloc(10*sizeof(char));
strcpy( ( *p[1] ).t, "test");
( *p[1] ).p = 10;

p [1]是指针。因此,您可以编写例如p [1] - > t,或者取消指针并获取结构类型的指向对象( *p [1]).t

It seems you mean the following

(*p[1] ).t = (char*)malloc(10*sizeof(char));
strcpy( ( *p[1] ).t, "test");
( *p[1] ).p = 10;

That is p[1] is a pointer. So you can write for example either p[1]->t or dereferencing the pointer and getting the pointed object of the structure type ( *p[1] ).t.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文