简体   繁体   English

我试图理解的字符串指针行为

[英]String pointer behaviour I am trying to understand

I have written a replacechar function which replaces an instance of a source char with a replacement char. 我已经编写了replacechar函数,该函数用替换char替换了源char的实例。 The function works in that the string is changed as expected but when I attempt to use the return value of the function, puts just outputs a blank line. 该函数的工作原理是按预期方式更改了字符串,但是当我尝试使用该函数的返回值时,put仅输出一个空行。

Can someone please explain what is happening and what I would need to change in replacechar to fix. 有人可以解释一下正在发生的事情以及我需要在replacechar中进行更改以解决的问题。

#include <stdio.h>  /* puts */
#include <string.h> /* strcpy */
#include <stdlib.h> /* malloc, free */

char* replacechar(char* s, char ch1, char ch2) {
   while (*s) {
      if (*s == ch1)
         *s = ch2;

      *s++;
   }

   return s;
}

int main()
{
   char* s = malloc(8);

   strcpy(s, "aarvark");

   puts(replacechar(s, 'a', 'z')); /* prints blank line */

   puts(s);  /* prints zzrvzrk as expected */

   free(s);

   return 0;
}

Thanks for all the responses. 感谢您的所有回复。

I have changed to this (which now works fine). 我已更改为此(现在可以正常工作)。

char* replacechar(char* s, char ch1, char ch2) {
   char* p = s;
   while (*p) {
      if (*p == ch1)
         *p = ch2;

      p++;
   }

   return s;
}

It returns the value of the s pointer once it's been incremented past the end of the string. 一旦它的值增加到字符串末尾,它将返回s指针的值。 Make a local variable in replacechar() , and increment it, and return the original value of s . replacechar()一个局部变量,并将其递增,然后返回s的原始值。

Thats because the while loop in replacechar increment s until it's \\0 . 那是因为replacecharwhile循环将s递增至\\0 At the end of the function you're returning the pointer, which points to \\0 and printing \\0 is a blank line. 在函数的最后,您将返回指向\\0的指针,并打印\\0为空行。 You should manage it like this: 您应该这样管理:

char *replacechar(char *s, char ch1, char ch2) {
    char *start = s;
    ...
    return start;
}

Your issue here, with otherwise pretty nice looking code, is one of variable scope. 您这里的问题,加上其他相当漂亮的代码,是可变范围之一。

Use a different local char* within replacechar, like 在replacechar中使用其他本地char *,例如

char* replacechar(char* s, char ch1, char ch2) {
   char* tmpstr;

   tmpstr=s;
   while (*tmpstr) {
      if (*tmpstr == ch1)
         *tmpstr = ch2;

      tmpstr++;  /* Note, no "*" here as in your code.  */
   }

   return s; /* s has remained unchanged */
}
#include <stdio.h>  /* puts */
#include <string.h> /* strcpy */
#include <stdlib.h> /* malloc, free */

char* replacechar(char* s, char ch1, char ch2) {
   char* t = s;
   while (*s) {
      if (*s == ch1)
         *s = ch2;

      *s++;
   }

  return t;
}

int main()
{
   char* s = malloc(8);

   strcpy(s, "aarvark");

   puts(replacechar(s, 'a', 'z')); /* prints blank line */

   puts(s);  /* prints zzrvzrk as expected */

   free(s);

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM