我遇到过这样的功能,对于我反转特殊类型单词的任务非常有用。我在 while 循环中遇到了复杂的指针算法问题。如何显示留在后面的数组索引号,例如。word
,dPtr
或subword
(在当前迭代中)与 printf ?
我只实现了减法值(subword-word)和(dPtr-dest)。
有没有办法创建一个“零”的“foo”指针,以便减法仅给出检查值?
这是代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char* subword = NULL;
char* dest;
char* dPtr;
size_t n, len;
int len_int, n_int;
char word[] = "-example-compound-word";
len = strlen(word);
len_int = (int)len;
printf("string length is %d\n", len_int);
dest = malloc(len+1);
if (dest == NULL) return -1;
dPtr = dest;
while((subword = strrchr(word, '-'))!= NULL) {
printf("the pointer values are: subword-word %ld, dPtr-dest %ld\n", (subword-word), (dPtr-dest));
n = len - (subword-word) - (dPtr-dest);
n_int = (int)n;
printf("and the n is %d\n", n_int);
if (n-1 > 0)
strncpy(dPtr, subword+1, n-1);
*subword = '\0';
dPtr += n-1;
*dPtr = '-';
dPtr++;
}
strncpy(dPtr, word, len - (dPtr-dest));
dest[len] = '\0';
printf("the output is %s\n", dest);
return 0;
}
提前致谢!