Click here to Skip to main content
Sign Up to vote bad
good
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 13 Jul '09 - 21:43
ksaw123425


6 solutions

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
  Permalink  
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 questionCool | :cool: !
  Permalink  
<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 />

Smile | :)

  Permalink  
this will work, its more simpler
 
strcpy(q,p);
  Permalink  
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'
  Permalink  
const char * p= "ddddd";
char q[500];
memset(q,0,500) ;
size_t plen = strlen(p) ;
strncpy(q,p,plen);
cout<<q<<endl ;
  Permalink  
  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 368
1 OriginalGriff 261
2 Mayur_Panchal 153
3 Mohammed Hameed 145
4 Dave Kreskowiak 125
0 Sergey Alexandrovich Kryukov 8,146
1 OriginalGriff 6,236
2 CPallini 3,482
3 Rohan Leuva 2,703
4 Maciej Los 2,234


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 28 May 2010
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid