c ++中的指针分配 [英] pointer allocation in c++

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

问题描述

我想实现类似的东西



i want to implement something like this

#include "StdAfx.h"
#include<iomanip>
#include <iostream>

using namespace std;

class node
{
	int data;
public:
	node *next;
	node(int d);
};
node::node(int d)
{
	data=d;
}

class Linklist
{
	node *start;
	node *next;
public:
	Linklist();
	void append(int d);
};
Linklist::Linklist()
{
	start=NULL;
}
void Linklist::append(int d)
{
	node *ptr=new node(d);
	ptr->next=NULL;
	start=ptr;
}
int main()
{
	Linklist l;
	l.append(10);
	l.append(20);
	return 0;
}



每次将append()的指针ptr分配给同一个地址,为什么?怎么做才能解决呢?


the pointer ptr at append() is assigned to same address every time , why? and what to do to solve it?

推荐答案

我能看到的第一个大设计错误是:从所有类成员中删除所有I / O,否则,你在创建什么,一个只能与 cin cout 一起工作的课程,没有别的吗?







关于你的问题: ptr1 不一定是分配给相同的地址,因为它被分配给新分配的内存位置。如果您多次重复分配和删除,可能就是这种情况,因此下一次分配只需要取消分配的内存。目前尚不清楚为什么要在代码中执行此操作。你应该查看它。





-SA
First big design mistake I can see is: remove all I/O from all class members, otherwise, what are you creating, a class which can only work with cin and cout, nothing else?



As to your question: ptr1 does not have to be assigned to the same address, as it is assigned to a freshly allocated memory location. It can be the case if you repeat allocation and deletion several times, so next allocation simply takes the piece of memory you just deallocated. It's not clear why do you do it in your code. You should review it.


—SA


这篇关于c ++中的指针分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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