I am writing a code that replace word-X with word-Y.
- every word in the text is in the same length.
- let say my string,X,Y are:
"aaa bbb ccc ddd qqq" , X = 2 , Y= 5
so it will print: "aaa qqq ccc ddd bbb"
but from some reason that i don't understand it throw me exception. i wrote in the code where is the error. I know my code is a little messy so if you have also suggestion i will happy to hear.
Thank you!!!
void changeWords(char *s,int X, int Y)
{
int len,words,i,count;
len = count = words = i = 0;
bool flag = false;
while (s[len] != ' ')
len++;
char *p1 = (char*)malloc(sizeof(char)*(len+1));
if (p1== NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
char *p2 = (char*)malloc(sizeof(char)*(len+1));
if (p2== NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
while (flag == false)
{
if (count == (X-1))
{
for(int x = 0; x< len;x++,i++)
p1[x] = s[i];
}
else if (count == (Y-1))
{
for (int x = 0; x< len; x++,i++)
p2[x] = s[i];
flag = true;
}
if (s[i] == ' ')
count++;
i++;
}
p1[len] = p2[len] = '\0';
i = count = 0;
flag = false;
while (flag == false)
{
if (count == (X-1))
{
for (int x = 0; x< len; x++, i++)
s[i] = p1[x]; // here it throw an error "Unhandled exception thrown:.."
}
else if (count == (Y-1))
{
for (int x = 0; x< len; x++, i++)
s[i] = p2[x];
flag = true;
}
if (s[i] == ' ')
count++;
i++;
}
puts(s);
free(p1); free(p2);
}
void main()
{
char*str = (char*)malloc(sizeof(char));
if (str == NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
char ch;
int i = 0;
printf("Enter a string: ");
while ((ch = getchar()) != '\n')
{
str[i] = ch;
i++;
str = realloc(str, sizeof(char) * (i + 1));
if (str == NULL)
{
printf("Error: memory did not allocated");
exit(1);
}
}
str[i] = '\0';
func(str,3,5);
printf("new string: %s\n", str);
free(str);
system("pause");
}
}