Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C++/CLI C MFC ATL WTL STL
Hi all

can you help?

part of my code i need to do this

const char * p= "ddddd";
char q[500];

I want to copy the sting in p to q[]?

Posted 13-Jul-09 21:43pm
ksaw123425
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

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  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

  const char * p= "ddddd";
  char q[500];
  int i;
  i=0;
  while (p[i] && i < sizeof(q) - 1 )
    q[i++] = p[i];
  q[i]='\0';

Smile | :)

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

this will work, its more simpler
 
strcpy(q,p);
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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
0 Sergey Alexandrovich Kryukov 269
1 OriginalGriff 220
2 Peter Leow 205
3 _Amy 190
4 Andreas Gieriet 180
0 OriginalGriff 7,540
1 Sergey Alexandrovich Kryukov 6,412
2 Maciej Los 3,849
3 Peter Leow 3,653
4 CHill60 2,702


Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 28 May 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100