concatenate char to string (c ansi)

M

mc

How can I concatenate a char to a string in C ?

I try this:
#include <stdio.h>
#include <string.h>

int main(void)
{

char *strExample;
char charExample;

charExample='a';
strExample[0]=charExample;
charExample='b';
strExample[1]=charExample;
strExample[2]='\0';

printf("%s",strExample);

return 0;
}

I can compile (gcc -ansi try.c -o try) but execution fail.
A string is an array of char...so, what's wrong?
 
I

Ike Naar

How can I concatenate a char to a string in C ?

I try this:
#include <stdio.h>
#include <string.h>

int main(void)
{

char *strExample;
char charExample;

charExample='a';
strExample[0]=charExample;
charExample='b';
strExample[1]=charExample;
strExample[2]='\0';

printf("%s",strExample);

return 0;
}

I can compile (gcc -ansi try.c -o try) but execution fail.
A string is an array of char...so, what's wrong?

You did not allocate any memory for the string.
One way to solve it is to define strExample as

char strExample[3];

You might want to have a look at question 7.1 of the C language FAQ at

http://c-faq.com/malloc/malloc1.html
 
B

Bichejo

mc   said:
How can I concatenate a char to a string in C ?
I try this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *strExample;
char charExample;
charExample='a';
strExample[0]=charExample;
charExample='b';
strExample[1]=charExample;
strExample[2]='\0';
printf("%s",strExample);

return 0;
}
I can compile (gcc -ansi try.c -o try) but execution fail.
A string is an array of char...so, what's wrong?

You did not allocate any memory for the string.
One way to solve it is to define strExample as

  char strExample[3];

You might want to have a look at question 7.1 of the C language FAQ at

 http://c-faq.com/malloc/malloc1.html- Hide quoted text -

- Show quoted text -

ok, this rule:

#include <stdio.h>
#include <string.h>

int main(void)
{

char strExample[20];
char charExample;

charExample='a';
strExample[0]=charExample;
charExample='b';
strExample[1]=charExample;
strExample[2]='\0';

printf("%s",strExample);

return 0;
}

Thanks.
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top