12,746,668 members (32,638 online)
Rate this:
See more:
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 22:43pm
ksaw123427

Rate this:

## 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
Rate this:

## 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 question:cool:!
Rate this:

## Solution 1

`<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 />`

:)

Rate this:

## Solution 2

this will work, its more simpler

strcpy(q,p);
Rate this:

## 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'
Rate this:

## 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 ;

Top Experts
Last 24hrsThis month
 ppolymorphe 177 OriginalGriff 140 Dave Kreskowiak 90 NightWizzard 80 Michael_Davies 80
 OriginalGriff 3,578 Peter Leow 2,741 ppolymorphe 1,925 Karthik Bangalore 1,700 Richard MacCutchan 1,319