Click here to Skip to main content
15,860,844 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi all

can you help?

part of my code i need to do this

const char * p= "ddddd";<br />char q[500];<br /><br />I want to copy the sting in p to q[]?<br /><br />
Posted

const char * p= "ddddd";
char q[500];
memset(q,0,500) ;
size_t plen = strlen(p) ;
strncpy(q,p,plen);
cout<<q<<endl ;
 
Share this answer
 
If you're programming in C, then:

strncpy( q, p, 499 );
q[499] = '\0';


will do the trick and work however long the string is. If you'd like to obfuscate things a bit more then you can combine the two lines into one by exploiting the return value of strncpy:

strncpy( q, p, 499 )[ 499 ] = '\0';


I wouldn't use the single line version unless you want extreme sarcasm deployed in code reviews. And a few cross eyed maintenance programmers.

Cheers,

Ash
 
Share this answer
 
strcpy(q,p); works fine.
but if(strlen(p)>500)
then
strncpy(q, p, 499);
q[500-1] = '\0';

q has to be terminated with '\0'
 
Share this answer
 
i think u can copy str like this:
if(strlen(p)<500)
{
  strcpy(q, p);
}
else
{
  strncpy(q, p, 500-1);
}


Pls feel free to contact me if any question:cool:!
 
Share this answer
 
this will work, its more simpler

strcpy(q,p);
 
Share this answer
 
<br />  const char * p= "ddddd";<br />  char q[500];<br />  int i;<br />  i=0;<br />  while (p[i] && i < sizeof(q) - 1 )<br />    q[i++] = p[i];<br />  q[i]='\0';<br />

:)

 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900