It should not be surprising that reverseWords
it does not print anything. Why?
char * reverseWords(char *line){
...
char *temp, *word;
...
line = temp;
return line;
}
line
? ( temp
). temp
? ( reverseWords
). temp
(none - )
, , reverseWords
, ? ( ...), , - char temp[strlen(line)+1] = "";
, reverseWords
Undefined Behavior, , , - reverseWords
, , reverseWords
...
? : (1) , :
char *revwords (char *rline, char *line)
(2) temp
, , temp
, reverseWords
(3) temp
reverseWords
line
temp
. (, strcpy
line = temp;
)
, reverseWords
, , , reverseWords
.
, argc
argv
, main
. , stdin
,
#include <stdio.h>
#include <string.h>
#define SIZE 256
char *revwords (char *rline, char *line);
int main (void) {
char line[SIZE] = "", rline[SIZE] = "";
while (fgets (line, SIZE, stdin)) {
printf ("\n line: %s\nrline: %s\n", line, revwords (rline, line));
*rline = 0;
}
return 0;
}
char *revwords (char *rline, char *line)
{
size_t lnlen = strlen (line);
char *p = line + lnlen - 1, *ep = p, *rp = rline, *p2space = NULL;
if (!line || !*line) {
fprintf (stderr, "revwords() error: 'line' empty of null.\n");
return NULL;
}
if (*ep == '\n')
*ep-- = 0;
else
fprintf (stderr, "warning: no POSIX '\\n' found in line.\n");
for (; ep >= line; ep--) {
if (*ep == ' ') {
size_t len = p - ep;
strncat (rp, ep + 1, len);
if (p == line + lnlen - 1)
strcat (rp, " ");
p = ep;
p2space = ep;
}
}
strncat (rp, line, p - line);
if (!p2space) {
fprintf (stderr, "revwords() error: nothing to reverse.\n");
return NULL;
}
return rline;
}
:, line
'\n'
, revwords
, , , SIZE
( , POSIX '\n'
), . .
/
$ printf "my dog has fleas\nmy cat does too\n" | ./bin/str_rev_words
line: my dog has fleas
rline: fleas has dog my
line: my cat does too
rline: too does cat my
, - . , , , . .
, - :
char *revwords (char *rline, char *line)
{
size_t len = strlen (line);
char *p = NULL, *p2space = NULL, copy[len+1];
if (!line || !*line) {
fprintf (stderr, "revwords() error: 'line' empty of null.\n");
return NULL;
}
if (line[len-1] == '\n')
line[--len] = 0;
else
fprintf (stderr, "warning: no POSIX '\\n' found in line.\n");
strncpy (copy, line, len + 1);
while ((p = strrchr (copy, ' '))) {
strcat (rline, p + 1);
strcat (rline, " ");
p2space = p;
*p2space = 0;
}
if (p2space) {
*p2space = 0;
strcat (rline, copy);
}
else {
fprintf (stderr, "revwords() error: nothing to reverse.\n");
return NULL;
}
return rline;
}
.. , C caMelCase
MixedCase
. caMelCase
MixedCase
java ++. ( , , - )