[英]Reversing tokens from strtok results in empty string
I am attempting to reverse the words/tokens returned from strtok, I am iterating over each token in reverse order and assigning each ith value to a buffer called new
.我试图反转从 strtok 返回的单词/标记,我以相反的顺序迭代每个标记并将每个第 i 个值分配给一个名为new
的缓冲区。 I can print each ith value/char of the token pointer p
but for some reason I am having trouble assigning the chars p
is pointing to the buffer new
.我可以打印标记指针p
的每个第 i 个值/字符,但由于某种原因,我无法分配字符p
指向缓冲区new
。 What am I missing or doing wrong here?我在这里错过了什么或做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char str[] = "This is an example!";
char *new = malloc(strlen(str));
char *p = strtok(str, " ");
size_t j = 0;
while (1) {
for (size_t i=strlen(p)-1; i>-1; i--) {
new[j++] = p[i];
}
p = strtok(NULL, " ");
if (!p)
break;
new[j++] = ' ';
}
printf("%s\n", new);
return 0;
}
stdout:标准输出:
Intended/expected output:预期/预期 output:
sihT si na !elpmaxe
new
because the initial value of the loop is strlen(p)
.终止空字符将被添加到new
的缓冲区中,因为循环的初始值为strlen(p)
。 It should be strlen(p)-1
.它应该是strlen(p)-1
。i
should be ssize_t
(signed type) instead of size_t
(unsigned type) to have i>-1
work well. i
的类型应该是ssize_t
(有符号类型)而不是size_t
(无符号类型)才能使i>-1
正常工作。new
and terminating null-character should be added at the end of string.应该为new
分配一个字节,并且应该在字符串末尾添加终止空字符。Try this:试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char str[] = "This is an example!";
char *new = malloc(strlen(str)+1); /* allocate one more byte */
char *p = strtok(str, " ");
size_t j = 0;
while (1) {
for (ssize_t i=strlen(p)-1; i>-1; i--) { /* fix loop */
new[j++] = p[i];
}
p = strtok(NULL, " ");
if (!p)
break;
new[j++] = ' ';
}
new[j] = '\0'; /* add terminating null-character */
printf("%s\n", new);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.