I need to manipulate an string in this way:
If the character is '+' or '-' or '/' or '*', move them to the end of buffer, if not, move to the beginning of the buffer.
My solution is quite simple:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void mix_the_string(char ** buff, char ** string)
{
printf("The string which will be printed is : %s\n",*string);
int i = 0;
int j = strlen(*string) - 1;
while(i< strlen(*string))
{
if(*string[i] != '+' || *string[i] != '-' || *string[i] != '*' || *string[i] != '/')
{
printf("in the first if, i = %d, *string[i] = '%d'\n",i,(int)*string[i]);
*buff[i] = *string[i];
}
else
{
printf("in the second if, i = %d, *string[i] = '%d'\n",i,(int)*string[i]);
*buff[j] = *string[i];
}
i++;
j--;
}
}
int main()
{
char * buff = (char *) malloc(50);
char * string = (char *) malloc(50);
string = "1+2+3";
mix_the_string(&buff,&string);
puts(buff);
free(buff);
free(string);
return 0;
}
The output of this code is:
The string which will be printed is : 1+2+3
in the first if, i = 0, *string[i] = '49'
in the first if, i = 1, *string[i] = '49'
Segmentation fault
I expected with this example that output would be like:
The string which will be printed is : 1+2+3
in the first if, i = 0, *string[i] = '49'
in the second if, i = 1, *string[i] = '43'
in the first if, i = 2, *string[i] = '50'
in the second if, i = 3, *string[i] = '43'
in the first if, i = 4, *string[i] = '51'
123++
Where am I going wrong?
int j = strlen(*string) - 1;ifstringis empty you get-1. UB...