Link to home
Start Free TrialLog in
Avatar of pgmerLA
pgmerLA

asked on

using strcpy in c++ error

Can you please tell me what's wrong with this code?
I need to use strcpy for my homework and I keep getting a "Run-time check failure #2:Stack around st2 was corrupted"

btw, I am trying to just print State

Thanks guys!
#include<iostream>
#include<cstring>

using namespace std;

int main(){
	char st1[20]="State of Ca";
	char st2[5]={' '};

	strcpy(st2, st1);
	cout<<st2<<endl;
	
return 0;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of crysallus
crysallus
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pgmerLA
pgmerLA

ASKER

is there any way I could use strcpy?
strcpy always copies the whole of the source (st1), into the destination (st2), as such the destination must be at least as large as the source, including null-terminating character.

So, to copy only "State", or have the destination string smaller than the source, no.
SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oops, crysallus, I didn't see that you said "including null-terminating character". So, never mind.
Actually, you were still kind of right to pick up on that, as I hadn't put 6 in my sample code in my first post, which I should have.

But yes, my explanation there probably should have got that across.
Avatar of pgmerLA

ASKER

Thanks guys.