Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to use char pointer with allocation in class in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class CClass {
	char *p;
	int len;
public:
	CClass();
	~CClass() { delete p; }
	CClass(char *s, int l);
	char *get() {
		return p;
	}
	int length() {
		return len;
	}
};

CClass::CClass() {
	p = new char[128];
	if (!p) {
		cout << "Allocation Error" << endl;
		exit(1);
	}
	*p = '\0'; 
	len = 128;
}

CClass::CClass(char *s, int _len) {
	if (strlen(s) >= _len) {
		cout << "Allocating size (_len) < string size (s)" << endl;
		exit(1);
	}

	p = new char[_len];
	if (!p) {
		cout << "Allocation Error" << endl;
		exit(1);
	}
	strcpy(p, s);
	len = _len;
}

int main()
{
	CClass o1, o2("c c++", 32);

	cout << "o1: " << o1.get() << " len: " << o1.length() << endl;

	cout << "o2: " << o2.get() << " len: " << o2.length() << endl;

	return 0;
}


/*
run:

o1:  len: 128
o2: c c++ len: 32

*/

 



answered May 25, 2018 by avibootz

Related questions

...