谁能告诉我为什么这段代码会这样? [英] Can anyone tell me why this code behaves this way?

查看:66
本文介绍了谁能告诉我为什么这段代码会这样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

struct cards
{
    int num;
    string suit;
    cards * next_card;
};

cards get_card(int num, string suit, cards *previous_card)
{
    cards card;
    card.num = num;
    card.suit = suit;
    card.next_card = previous_card;
    return card;
}

int main()
{
    cards *temp_card = NULL;
    string suit;

    for (int i = 0; i<4; i++)
    {
        if (i == 0){suit = "hearts";}
        if (i == 1){suit = "diamonds";}
        if (i == 2){suit = "clubs";}
        if (i == 3){suit = "spades";}
        for (int j = 0; j<13; j++)
        {
            cards sum_card = get_card(j+1, suit, temp_card);
            temp_card = &sum_card;
        }
    }
    while ((*temp_card).next_card != NULL)
    {
        cout <<(*temp_card).num <<" of ";
        cout <<(*temp_card).suit <<"\n";
        temp_card = (*temp_card).next_card;
    }
    cout <<"yis it work";
}





这是为了打印一副卡片中的所有卡片,但它只打印同一张卡片,无限地再次。谁能发现问题?



我尝试过:



sum stuf ................................................ .......................



This is meant to print all the cards in a deck of cards but it just prints the same card over and over again infinitely. Can anyone spot the problem?

What I have tried:

sum stuf.......................................................................

推荐答案

因为只有一张卡存在:并且你会一直覆盖它。

如果你为一个循环内部或外部声明一个变量并不重要:只创建一个变量,你不会得到一个全新的变量你绕过循环。

为了证明这一点,请查看每次使用的地址并使用调试器存储在temp_card中 - 它将始终是相同的地址。



每次使用新卡时,你需要使用一个数组(可能是最好的一副牌)或 malloc 给你一个新的区域用于存储卡信息的内存。
Because only one card exists: and you keep overwriting it.
It doesn't matter if you declare a variable inside or outside a loop for this: only one variable is created, you do not get a "brand new one" each tine you go round the loop.
To prove this, look at the address you take each time and store in temp_card with the debugger - it will always be the same address.

To use anew card each time, you need to use either an array (probably the best for a deck of cards) or malloc to give you a new area of memory to store your card info in.


是一个链表,您必须使用 malloc()。

cards is a linked list, you must allocated each node manually using malloc().
cards get_card(int num, string suit, cards *previous_card)
{
    cards card; // here is the memory problem
    card.num = num;
    card.suit = suit;
    card.next_card = previous_card;
    return card;
}



这段代码动态分配一个卡片节点,问题是该节点释放了从函数返回的代码。

说不然,代码只是弄乱了内存。

malloc - C ++ Reference [ ^ ]

-----

你的代码没有你想象的那样,你不明白为什么!



那里是一个几乎通用的解决方案:逐步在调试器上运行代码,检查变量。

调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

调试器中没有魔法,它不知道你应该做什么,它没有发现错误,只是通过向你展示发生了什么来帮助你。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行,并在执行时检查变量。

调试器 - 维基百科,免费的百科全书 [ ^ ]



掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]

这里的调试器只显示你的代码正在做什么,你的任务是与它应该做什么进行比较。


This code dynamically allocate a node of cards, the problem is that the node is freed the code return from the function.
Said otherwise, the code is just messing with the memory.
malloc - C++ Reference[^]
-----
Your code do not behave the way you expect, and you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


如果那是在链表上的练习那么正如其他人已经注意到的那样,你必须在linekd列表上运用更多。

另一方面,如果你真的需要在 C ++ 程序中处理一副牌,那么链表可能不是更好选择。试一试

If that is meant as an exercise on linked list then you, as others already note, have to exercise more on linekd list.
On the other hand, if you really need to handle a deck of cards in a C++ program, then a linked list is possibly not the better choice. Try for instance
#include <vector>
#include <array>
#include <iostream>
using namespace std;

constexpr int VALUES = 13;
constexpr int SEEDS = 4;
constexpr int CARDS = VALUES * SEEDS;


class Card
{
  int v;

public:
  Card(int v):v(v){}
  int getValue() const { return (v % VALUES);}
  int getSeed() const { return (v / VALUES);}
  string getSeedDesc() const;
};

ostream & operator << ( ostream & os, const Card & card);


int main()
{
  vector <Card > card;

  for ( int n = 0; n < CARDS; ++n) card.emplace_back(Card(n));

  for (const auto & c : card) cout << c << endl;
}


ostream & operator << ( ostream & os, const Card & card)
{
  os << card.getValue() << " of " << card.getSeedDesc();
  return os;
}

string Card::getSeedDesc() const
{
  static array<string, SEEDS> desc = { "hearts", "diamonds", "clubs", "spades" };
  return desc[getSeed()];
}


这篇关于谁能告诉我为什么这段代码会这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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