12,068,108 members (50,594 online)
Rate this:
See more:
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 22:43pm
ksaw123423

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

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

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
 Dave Kreskowiak 290 CPallini 232 CHill60 214 Richard MacCutchan 195 Richard Deeming 184
 Dave Kreskowiak 2,121 Richard MacCutchan 1,455 OriginalGriff 1,451 CPallini 1,042 d@nish 980