My goal:

  1. In the function zad2() pass the argument s , which is an array of characters / string ( char s[] ).
  2. In the function zad2(char s[]) I find the penultimate word in the line and after each of its letters I insert the symbol * .
  3. Return processed s to main function.

I have the following features:
Search for a space to highlight a word.

 char* next_to_last(char* str) { char* end = &str[strlen(str)]; while (*end == ' ') end--; while (*end != ' ') end--; while (*end == ' ') end--; while (*end != ' ') end--; end++; return end; } 

Passage by word using the first function:

 void zad2() { char buf[BUFSIZ]; while (printf("Введите строку для задания: ") && fgets(buf, 81, stdin) && *buf!='\n') { for(char* word = next_to_last(buf); !strchr(DELIM, *word); word++) { for (char* ptr = &word[strlen(word)]; ptr>word; ptr--) { *(ptr+1) = *ptr; } *++word = '*'; } puts(buf); } } 

The essence of the problem is that I need not to enter the string through fgets() , as in the second function, but immediately work with the transmitted s and return it to main .

  • The essence of the problem is completely incomprehensible. And what is related to it all the above code is also not clear. It is necessary - do not enter a string, but pass it on with an argument, does someone interfere? - PinkTux
  • The problem is just that it does not work for me to replace all this canoe with buf with its variable. It prevents my ignorance, in connection with which I ask for help. - A_lina19
  • Uh ... void zad2(char s[], char buf[]) { . Everything. - PinkTux
  • I have a global variable s in which there is text. I need to pass it to the zad2() function for processing. From buf I just need to get rid of myself and make all changes in s . - A_lina19
  • Global variables do not need to be transferred anywhere, they are already visible from the function. But if we take for granted that global variables are evil, then the variable s passed to the function as a normal parameter: void zad2(char *s) or void zad2(char s[]) . You are next_to_last() argument to next_to_last() (we will not talk about its strangeness), what’s the problem with doing the same thing? - PinkTux

1 answer 1

So, here is the result of the changes:

 char *zad2(char *buf) { buf[80] = 0; for(char* word = next_to_last(buf); !strchr(" ", *word); word++) { for (char* ptr = &word[strlen(word)]; ptr>word; ptr--) { *(ptr+1) = *ptr; } *++word = '*'; } return buf; } 

Then out = zad2(some_string_outside) main() is called in main() and out = zad2(some_string_outside) via puts(out) or printf("%s", out)