When I try to run this code it successfully asks me for a string and assigns it to the inpstr. When I call the deblank function i get "zsh bus error" Any help would be highly appreciated.
int main()
{
//Problem 1 Code
//Declare a string and assign user input to it with fgets and chomp it
char inpstr[20];
char outstr[20];
printf("Enter a string: ");
fgets(inpstr, 20, stdin);
chomp(inpstr);
//Call deblank to assign the copied string without whitespace to outstr
deblank(inpstr, outstr);
return 0;
}
void chomp(char word [])
{
if(word[strlen(word) - 1] == '\n')
{
word[strlen(word) - 1] = '\0';
}
}
void deblank(char *inpstr, char *outstr)
{
//First we find the length of the string not including the null
int length = strlen(inpstr);
//declare a counting variable
int o;
//For loop to check each letter
for(int i = 0; i < length; i++)
{
if(inpstr[i] != ' ')
{
outstr[o] = inpstr[i];
o++;
}
}
}
I have tried a few different things to maybe redefine the pointers, but nothing changed. Either got a compiling error or another zsh bus error. I have deleted code up to the int length = strlen(inpstr) and tested it and it runs correctly. I believe the error begins with the for loop in the deblank function. All the function prototypes were typed above the main function and libraries were also included.
There are several problems.
First of all the variable
owas not initialized.So using it as an index
invokes undefined behavior.
Another problem is that the array
outstrwill not contain a string because you forgot to append the terminating zero character '\0' to the stored sequence of characters in the array.The function
deblankcould be defined the following way. Pay attention to that you should also remove tab characters'\t'. And using within the function the functionstrlenis inefficient. The function can be more simpler without declaring additional variables.If you want to remove only the space character
' 'then the header<ctype.h>is not needed and the if statement within the function will look asAnd at last the function
chompalso can invoke undefined behavior if an empty string will be passed to it because the expression
strlen(word) - 1will produce a big positive number.Instead of using your manually written function you could just write in main