I am doing my homework, the problem is as follows:
- accept words separated by commas.
- extracted each word and reverse them.
- put them back in order.
for example, if I enter "apple,egg", I get "elppa,gge"
So far I've completed most of the program, the program works well when I enter less than four words, but with more than four words such as "ybur,etaga,etiluzal,iluzal sipal,etihcalam" the program doesn't work and it shows me return value 3221225477. I just learned how to use dynamical memory allocation so I think it may result from the fact that I did not use it properly, if that's true, please correct me.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int c=1,i,s;
char a[1000];
fgets(a,1000,stdin);
for(i=0;i<strlen(a);i++){
if(a[i]=='\n'){
a[i]='\0';
}
}
for(i=0;i<strlen(a);i++){
if(a[i]==','){
c++;
}
}
char **b;
b=(char**)malloc(sizeof(char)*c);
for(i=0;i<c;i++){
b[i]=(char*)malloc(sizeof(char)*100);
}
strcpy(b[0],strtok(a,","));
for(i=1;i<c;i++){
strcpy(b[i],strtok(NULL,","));
}
char **d;
d=(char**)malloc(sizeof(char*)*c);
for(i=0;i<c;i++){
d[i]=(char*)malloc(sizeof(char)*strlen(b[i]));
for(s=0;s<strlen(b[i]);s++){
d[i][s]=b[i][strlen(b[i])-s-1];
}
}
printf("%s",d[0]);
for(i=1;i<c;i++){
printf(",%s",d[i]);
}
for(i=0;i<c;i++){
free(b[i]);
free(d[i]);
}
free(b);
free(d);
return 0;
}
I hope that the program works no matter what words I enter.