Hello!
I'm new in C++, and I have a basic question:

When I have a function:

void foo(str* s){
char* p;
p = new char[strlen(s)];
strcpy(p, s);
cout << s <<endl;

}

This function will take the length of s and in bytes and will allocate that much space in memory for p.
I want to do the same but ask the user to enter a string and then dynamicly allocate memory for the entered string, but it wouldnt compile for some reason, and i'd get a segmentation error. I know I can print s right away, but i want to allocate memory dynamicly in this exersize.
Here is the code I have so far:

int main(void){

	char* s;
	char* p;
	cout << "Please Enter a string: ";
	cin >> s;
	p = new char[strlen(s)];
	strcpy(p, s);
	cout << p <<endl;
	return 0;
}

Any help would be greatly appreciated.
Thank you!

You forgot to allocate +1 byte for zero char terminating C-string:

p = new char[strlen(s)+1];

Now you have memory leak: you forgot to deallocate this memory:

delete [] p;

Well, it's evidently useless function...

The 2nd snippet:

char* s;
...
cin >> s;

Pointer variable s is not initialized, it points to nowhere, but you are trying to get a string in this undefined memory. The 2nd error: the same as in the 1st snippet.

It's C++ program, use C++ constructs (more robust and comfortable):

cout << "Please Enter a string: ";
string line;
getline(cin,line);
cout << line << endl;

Feel the difference ;)

You cannot get input to pointer s without first allocating it some memory. What you're doing is attempting to store to whatever memory address s points to, which could be pretty random!

If you've not allocated the memory, you don't control it. If you don't control it, you should not be trying to modify it.

And, when you allocate memory to hold a copy of a string, you need to use strlen( source ) +1 as the size of the new array - you've got to allow for the NULL terminator character.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.