简体   繁体   English

指针不起作用

[英]Pointer doesnt work

My code: 我的代码:

#include<iostream>

using namespace std;

struct element
{
    int liczba;
    element *nastepny;
    element();
};

element::element()
{
    nastepny=0;
}

int main()
{
    element pierwszy;
    pierwszy.liczba=1;
    element drugi;
    (*nastepny).pierwszy=2;
    drugi.liczba=2;
    return 0;
}

It says that *nastepny was not declared, but I do not know how is it possible. 它说* nastepny未声明,但我不知道怎么可能。 I created structure with *nastepny. 我用* nastepny创建了结构。 If I write element *nastepny, it says that element has no member named pierwszy. 如果我编写元素* nastepny,则表示该元素没有名为pierwszy的成员。 SOmething is going wrong because pierwszy is declared at the beginning of main function. 发生错误是因为在主函数的开头声明了Pierwszy。

(*nastepny).pierwszy=2;

That makes no sense as nastepny is not declared statically or within its current or any parent scope. 这是没有意义的,因为nastepny不是静态声明的, nastepny是在其当前或任何父范围内声明的。 It is a member of your structure and only exists as a part of and instance of one. 它是结构的成员,并且仅作为结构的一部分和实例而存在。

Also, you cannot simply assign two to the address of some unallocated pointer. 同样,您不能简单地将2分配给某些未分配指针的地址。 You have a pointer, but it does not yet point anywhere valid. 您有一个指针,但它尚未指向任何有效的地方。 So, either: 因此,要么:

drugi.nastepny = malloc(sizeof *drugi.nastepny);
*drugi.nastepny = whatever;

To allocate space dynamically, or... 动态分配空间,或...

drugi.nastepny = &some_variable;

But watch for lifetime issues on that last one. 但是要注意最后一个问题。

The error happens in 错误发生在

(*nastepny).pierwszy=2;
  ^^^^^^^^

nastepny is not declared in this scope. 未在此范围内声明nastepny The member of the struct doesn't make it accessible outside the struct (instances). 结构的成员无法使其在结构(实例)之外访问。

I guess you are meaning something like this: 我想你的意思是这样的:

drugi.nastepny = &pierwszy;
drugi.nastepny->liczba = 2;

我建议这样做:

pierwszy.nastepny = &drugi;

I'm not sure how you expect to get an object when you deference your pointer when you never assigned it a memory address? 我不确定在从未分配对象内存地址的情况下尊重指针时如何期望得到对象?

If you want to get a pointer to the object itself then you can use the this pointer. 如果要获取指向对象本身的指针,则可以使用this指针。 However in this scenario such an application of it would make no sense. 但是,在这种情况下,这样的应用是没有意义的。

The only assignment you provided to the element pointer was 0 (NULL), so it's not pointing to any element object. 您提供给元素指针的唯一分配是0(NULL),因此它没有指向任何元素对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM