Reputation: 73
i want to success two cases
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void append(char* s, char c){
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main()
{
char resultat[]="";
char str[]="hello world!";
int len=strlen(str);
printf("******* case 01 *******");
for(int i=0;i<len;i++){
strcat(resultat,str[i]);
}
printf("resultat = %s",resultat);
printf("******* case 02 *******");
for(int i=0;i<len;i++){
append(resultat,str[i]);
}
printf("resultat = %s",resultat);
return 0;
}
How can I add chars to a string? I tried this but I get this error:
******* case 01 *******
Process returned -1073741819 (0xC0000005) execution time : 4.676 s
Press any key to continue.
Upvotes: 0
Views: 1641
Reputation: 39
In C you need to make sure the destination variable has enough memory to store the stuff you want to copy there.
strcat needs a string (char *).
Here is my fixed version of your code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void append(char *s, char c)
{
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}
int main()
{
char str[] = "hello world!";
int len = strlen(str);
char resultat[len * 3];
resultat[0]='\0';
printf("******* case 01 *******\n");
char tmp[2];
tmp[1] = '\0';
for (int i = 0; i < len; i++)
{
tmp[0] = str[i];
strcat(resultat, tmp);
}
printf("resultat = %s\n", resultat);
printf("******* case 02 *******\n");
for (int i = 0; i < len; i++)
{
append(resultat, str[i]);
}
printf("resultat = %s\n", resultat);
return 0;
}
Upvotes: 1