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!
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;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
So, to copy only "State", or have the destination string smaller than the source, no.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
But yes, my explanation there probably should have got that across.
ASKER
Thanks guys.
ASKER