I have to make a function, that will code my sentence like this: I want to code all words with an o, so for example I love ice cream becomes I **** ice cream.
But my function ignores the result of strchr. And I don't know why.
This is my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define LEN 1000
char *Shift(char *str, char *let) {
const char *limits = " ,-;+.";
char copy[LEN];
strcpy(copy, str);
char *p;
char *ptr;
ptr = strtok(copy, limits);
for (int j = 0; ptr != NULL; ptr = strtok(NULL, limits), ++j) {
int len = 0;
if (strchr(ptr, let) != NULL) {
p = strstr(str, ptr);
for (int i = 0; i < strlen(ptr); i++) {
p[i] = "*";
}
}
}
return str;
}
int main() {
char *s = Shift("I love my cocktail", "o");
puts(s);
}
Expected output is: I **** my ********
but I've got just printed the original string
For starters the function
strchris declared likethat is its second parameter has the type
intand the expected argument must represent a character. While you are calling the function passing an object of the typechar *that results in undefined behaviorIt seems you mean
Also you may not change a string literal. Any attempt to change a string literal results in undefined behavior and this code snippet
tries to change the string literal passed to the function
And moreover in this statement
you are trying to assign a pointer of the type
char *to a character. At least you should writeIf you want to change an original string you need to store it in an array and pass to the function the array instead of a string literal. For example
Pay attention to that there is no great sense to declare the second parameter as having the type char *. Declare its type as char.
Also the function name
Shiftis confusing. You could name it for example likeHideor something else.Here is a demonstration program.
The program output is
The for loop
within the function can be rewritten as a call of
memset