简体   繁体   English

如何将代码从指针更改为结构数组的指针?

[英]How can I change a code from pointers to pointers to struct arrays?

I have to change a 23000 lines code from pointers to pointers to struct arrays, the next code is an example, but if I solve the problem here that will be enough. 我必须将23000行代码从指针更改为指向结构数组的指针,下面的代码是一个示例,但是如果我在这里解决问题就足够了。 I get the error: invalid type argument of unary '*' (have 'int'). 我收到错误:一元'*'的无效类型参数(具有'int')。 If I write int *content that allows the code to run, but I have to write int=content and change the code *((ptab->content)+pC1+17) , I tried but I can't fix the error. 如果我编写允许运行代码的int *content ,但是我必须编写int=content并更改代码*((ptab->content)+pC1+17) ,我尝试了但无法解决错误。

This is the example code in pointers to struct arrays 这是指向结构数组的指针中的示例代码

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
#include <Windows.h>

using namespace std;

struct box{
    int content;
};
struct box *ptab;

int pC1=5;

int main (){
    ptab=new struct box[64];

    if (*((ptab->content)+pC1+17)==0) {
        pC1=pC1+17;
    }
    cout<<pC1<<endl;
}

And this is the code in pointers, that already works. 这是指针中的代码,已经可以使用了。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <conio.h>
#include <iomanip>
#include <stdio.h>
#include <Windows.h>

using namespace std;

int *box;

int pC1=5;

int main (){
    box=new int[64];

    if (*(box+pC1+17)==0){
                                        pC1=pC1+17;
                                    }
    cout<<pC1<<endl;
}

Those are the examples, I would like to khow how to change from one code to the other, thanks. 这些是示例,我想知道如何从一种代码更改为另一种代码,谢谢。

In the bottom (working) code snippet, you're adding address offsets to an int pointer and dereferencing from that. 在底部的(有效的)代码片段中,您正在将地址偏移量添加到int指针并从中取消引用。 That is, you're properly dereferencing a pointer. 也就是说,您正在正确地取消引用指针。

In the top (nonfunctional) code snippet, you're adding address offsets to an int (not a pointer) and trying to dereference that, which isn't gonna work. 在最上面的(非功能性的)代码片段中,您要向int (而不是指针)添加地址偏移量,并尝试取消引用该地址偏移量,这将不起作用。

The code remains essentially the same. 代码基本上保持不变。 Pointer arithmetic works the same way regardless of the type. 无论类型如何,指针算术都以相同的方式工作。 It's just that when you have the address of a struct, you need to specify which member you want with -> 只是当您具有结构的地址时,您需要指定要使用的成员->

#include <iostream>
using namespace std;

struct box{
    int content;
};
struct box *ptab;

int pC1=5;

int main (){
    ptab=new struct box[64];

    if ((ptab+pC1+17)->content==0) {  // you could also do (*(ptab+pC1+17)).content
        pC1=pC1+17;
    }
    cout<<pC1<<endl;
}

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

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