指针对象(指针算术) [英] Pointer To Object (Pointer Arithmetic)

查看:75
本文介绍了指针对象(指针算术)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HellO Guys .. :)



首先,这不是家庭作业。这是我的实验室测试。

所以,我真的需要你的帮助..



实际上我想做的是找到学生的最高CGPA。 />
这是我的代码..

HellO Guys .. :)

First of all this is not the home work. This is my Lab Test .
So, i really need your help here ..

Actually I want to do is find the Maximum CGPA Of A Student.
here is my code ..

#include <iostream>
#include <iomanip>
using namespace std;

class Student
{
public:
    void GetData(Student *student, int size);
    void PrintData(Student *student, int size);
    void is_greater(Student *student, int size);
    Student();
private:
    int RollNo;
    float CGPA;
};
Student::Student()
{
    RollNo = 0;
    CGPA = 0;
}

void Student::GetData(Student *student, int size)
{
    for(int i = 0; i < size; i ++)
    {
        cout << "\t" << "## STUDENT ## {" << i +1 << "}" << endl;
        cin >> student->RollNo;
        cin >> student->CGPA;
        student++;
    }

}
void Student::PrintData(Student *student, int size)
{
    cout << setw(8) << "ROLLNO" << setw(16) << "CGPA" << endl;

    for(int i = 0; i < size; i ++)
    {
        cout << setw(8) << student->RollNo << setw(16) << student->CGPA << endl;
 //      *(student++);
        student ++;
    }

}

void Student::is_greater(Student *student, int size)
{
    float min_cgpa = student->CGPA; //min_cgpa = student[0].CGPA;
    int pos;
    for(int i = 0; i < size; i ++)
    {
            if(student->CGPA > min_cgpa)    //if(student[i].CGPA > min_cgpa)
            {
                min_cgpa = student->CGPA;   //min_cgpa = student[i].CGPA;
                pos = i;

            }
            student++;
    }
//    cout << "\t" << "Index Of Highest GPA -> " << (pos +1) << " That Is " << min_cgpa << endl;
    cout << "\t" << "... Student With Highest CGPA ..." << endl;
    cout << "\t" << student[pos].RollNo << "\t"  << student[pos].CGPA << endl;
}

int main()
{
    const int size = 3;
    Student *student = new Student[size];
    student->GetData(student, size);
    student->PrintData(student, size);
    student->is_greater(student, size);
    return 0;
}





语句cout<< \t<<学生[pos] .RollNo<< \t<<学生[pos] .CGPA<< endl;

导致未定义的行为.. POS 的值是正确的,但当我用作索引时,它将打印垃圾..

在使用调试器和观察窗口之后,我仍然无法跟踪错误..



简单地说,我无法理解火箭科学的背后...... ??!br />


请任何人精心准备这个..

我知道有很多方法可以做到这一点..

但是我想要它在我的方式..



建议会得到赞赏.. !!!!



The statement cout << "\t" << student[pos].RollNo << "\t" << student[pos].CGPA << endl;
cause the undefined behavior .. The value of POS is correct but when i use as index it will print the garbage ..
After using debugger and watch windows, i still unable to track the error ..

Simply Sir I unable to understand the Rocket Science Behind That .. ??!

Please ANYONE ELABORATE THIS ..
I Know There Are A Lot Of Methods To Do That ..
But I Want It In My Way ..

Suggestions Would Be Appreciated .. !!!!

推荐答案

你真正的问题不是指针算术(你实际上使用了很多索引算术,功能相同但更安全,并且你正确使用它),你的问题就是你问的问题。仔细观察:在你的代码示例中,你有 student [pos] .RollNo (这是正确的并且应该可行),在代码示例下的文本中你有学生[pos + 1] .RollNo ,这是不正确的,会导致问题。







正如我刚才注意到的,您的代码示例也是错误的:您不应该执行 *(student)++ ,因为它造成同样的问题。



[结束编辑]



使用索引没有错,但+1会产生尝试访问数组末尾后面的对象的情况。你在0 .. 2中运行循环,并且数组的大小是3.到目前为止,这么好。但索引 pos + 1 将变为3,这超过了为阵列分配的内存。这就是全部。



下次,请确保代码示例中显示的代码与您运行的代码完全相同。使用复制粘贴而不对代码进行任何修改,以显示相关问题。



-SA
Your real problem is not exactly the pointer arithmetic (you are actually using much index arithmetic, functionally the same, but safer, and you use it correctly), your problem is the way you ask the question. Look thoroughly: in your code sample, you have student[pos].RollNo (which is correct and should work), in the text under code sample you have student[pos+1].RollNo, which is incorrect and would cause the problem.



As I just noticed, your code sample is also wrong: you should not do *(student)++, as it creates the same problem.

[END EDIT]

There is nothing wrong with you use of indexes, but +1 creates the situation where you try to access the object behind the end of the array. You run the loop in 0 .. 2, and the size of the array is 3. So far, so good. But the index pos+1 would become 3, which is past the memory allocated for the array. That's all.

Next time, please make sure that the code shown in your code sample is exactly the same as the one you run. Use copy-paste without any modifications to the code which manifests the problem in question.

—SA


如果您正在寻找最大的CGPA,为什么要将变量命名为min_cgpa?只是为了迷惑读者 - 或者你自己:-)

通过阅读你的代码我可以发现一些事情:



(a)问问自己当第一个学生是具有最大CGPA的学生时会发生什么。在这种情况下,pos会被分配任何值吗?



(b)如果pos是最大值的索引,为什么要访问学生[pos + 1],正如你在下面的文字中建议你的代码? pos可以具有size-1的值,在这种情况下,你将访问一个未定义的对象。



(c)你打算用什么行

If you are looking for the maximum CGPA, why do you name your variable min_cgpa? Just to confuse the reader -- or yourself :-)

By just reading your code I can spot a couple of things:

(a) Ask yourself what happens when the first student is the one with the maximum CGPA. Does pos get assigned any value in that case?

(b) Why would you want to access student[pos+1] if pos is the index of the maximum, as you suggest in the text below your code? pos could have the value of size-1 and in that case you would be accessing an undefined object.

(c) What do you intend with the line
*(student)++; // misleading!



你可能想写:


You probably meant to write:

++student;



更简单,更直观(更安全)的是在这些循环中访问student [i]。否则,如果您将学生指针增加一次太多或太少,您将最终访问错误的对象。



当然,这不是作业: - )


And even simpler and more intuitive (and safer) would be to access student[i] in those loops. Otherwise, if you increment the student pointer one time too much or too little you will end up accessing the wrong objects.

And, of course, this is no homework :-)


以下是一些建议:



- 停止搞乱指针,数组和动态内存分配。他们99%的时间都不值得麻烦,这不是1%。



- 了解标准库 - std :: vector std :: max_element 让你的问题相对微不足道......



- ...但前提是你知道如何编写支持其操作的类。看看如何写 operator<



你的C ++教育迟早要用指针的东西。在此之前,他们就像一瓶装有rohypnol的啤酒一样对待它们 - 使用它们,你会因为屁股的疼痛而感到肮脏。如果您觉得使用指针的冲动,那么请考虑为什么要使用它并且:



- 如果您想表示所有权,请考虑使用智能指针 - std :: unique_ptr std :: shared_ptr 是好赌注



- 如果你想在集合中表示迭代,那么考虑使用迭代器



- 如果你想使用动态分配的数组,那么考虑使用 std :: vector 而不是



了解这个地段,你将能够在更少的时间内解决问题超过20分钟。
Here are some suggestions:

- stop messing about with pointers, arrays and dynamic memory allocation. They're not worth the hassle 99% of the time and this isn't the 1% that is

- learn about the standard library - std::vector and std::max_element makes your problem relatively trivial...

- ...but only if you know how to write a class that supports their operation. Check out how to write operator<.

Sooner or later in your C++ education you'll have to use pointers for something. Until then treat them like a bottles of lager spiked with rohypnol - use them and you'll wake up feeling dirty with a pain in your bum. If you feel the urge to use a pointer then consider why you want to use it and:

- if you want to represent ownership consider using a smart pointer - std::unique_ptr or std::shared_ptr are good bets

- if you want to represent iteration across a collection then consider using an iterator

- if you want to use a dynamically allocated array then consider using a std::vector instead

Get your head around this lot and you'll be able to turn a solution out in less than 20 minutes.


这篇关于指针对象(指针算术)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆