Why can I not do this:
char* p = new char[10];
void SetString(char * const str)
{
p = str;
}
SetString("Hello");
I have a const pointer to a char, why can I not assign the const pointer to another pointer?
It just seems illogical, as by assigning it to another pointer, you are not essentially violating the const-ness of the char pointer. Or are you?
EDIT: When I compile this it says "error C2440: '=' : cannot convert from 'char *const *__w64 ' to 'char *'"
(I'm attempting to understand a concept from a book I'm reading. Just cannot get the code to compile.
CODE:
int _tmain(int argc, _TCHAR* argv[])
{
MyString *strg = new MyString(10);
strg->SetString("Hello, ");
MyString *secondstr = new MyString(7);
secondstr->SetString("Tony");
strg->concat(*secondstr, *strg);
}
CPP FILE:
#include "MyStringClass.h"
#include <string.h>
#include "stdafx.h"
#include "MyStringClass.h"
void MyString::concat(MyString& a, MyString& b)
{
len = a.len + b.len;
s = new char[len + 1];
strcpy(s, a.s);
strcat(s, b.s);
delete [] s;
}
void MyString::SetString(char * const str)
{
s = str;
}
MyString::MyString(int n)
{
s = new char[n+1];
s[n+1] = '\0';
len = n;
}
HEADER FILE:
#include <string.h>
#include <stdio.h>
class MyString
{
private:
char* s;
int len;
public:
MyString(int n = 80);
void SetString (char * const str);
void concat (MyString& a, MyString& b);
};