strcpy and strcat problem

A

amanayin

#include<stdio.h>
#include<string.h>
int main(void)
{
char a[3] = "ab";
char b[3] = "cd";
char c[5] = " ";
strcpy(c,a);
strcat(c,b);
printf("a is %s\n",a);
printf("b is %s\n",b);
printf("c is %s\n",c);
}

See your problem
 
A

Al Bowers

amanayin said:
#include<stdio.h>
#include<string.h>
int main(void)
{
char a[3] = "ab";
char b[3] = "cd";
char c[5] = " ";
strcpy(c,a);
strcat(c,b);
printf("a is %s\n",a);
printf("b is %s\n",b);
printf("c is %s\n",c);
}

See your problem


Other than function main not returning an int, what is the problem?

The char array a[3] has been initialized and a points to a string "ab".
The char array b[3] has been initialized and b points to a string "cd".
The char array c[5] is different. There is enough space in
the array to store the five space characters, ' ', but
not for a terminating null character. So the null character
is not included and c is simply an array of five space
characters. It is not a string. But this is not a problem in this
code.
The function strcpy copies the string pointed to by a into the
char arrary pointed to by c. c is now a string "ab".
The function strcat appends the string pointed to by b onto the
string pointed to by c. c now points to the string "abcd".
Since there is enough storage for the operations and there is
no overlapping of objects, the code is ok.
 
D

Dave Thompson

char a[2]="ab";

The string "ab" actually has three chars ('a', 'b' and the terminating NUL
character '\0'), but you've only allocated two in array a[]. <snip>
Right.

char c[4]=" \0";

Ditto.

Note that c[] may hold only three characters plus the terminating NUL, so
you'll want to increase the allocated space in preparation for your string
concatenation below:

char c[5] = '\0'; /* 4 chars + terminating NUL */
You can't initialize an array to a single expression, because no
full-expression can have array type. Either = { '\0' } or = "" .

<snip>

- David.Thompson1 at worldnet.att.net
 
R

Robert B. Clark

Note that c[] may hold only three characters plus the terminating NUL, so
you'll want to increase the allocated space in preparation for your string
concatenation below:

char c[5] = '\0'; /* 4 chars + terminating NUL */
You can't initialize an array to a single expression, because no
full-expression can have array type. Either = { '\0' } or = "" .

You are of course correct.

What I had intended to write was

char c[5] = {'\0'};

Silly me for not proofreading carefully enough.

Thanks for the correction.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top