简体   繁体   English

为什么我的角色功能崩溃?

[英]Why does my character function crash?

I'm working on a project meant to create functions to perform different actions, but I'm having trouble implementing one of the functions. 我正在一个旨在创建功能来执行不同操作的项目中,但是我无法实现其中一个功能。

int main()
{
    char str1[30] = "Hello";
    char str2[30] = "Goodbye old friend";
    char str3[30];

    char *p = strCopy(str3, "Annie");
    printf("(Annie) %s\n", p);

    p = strString(str3, "nn");
    printf("(nnie) %s\n", p);

    strCopy(str3, "HeloHellooo");
    p = strString(str3, "ello");
    printf("(ellooo) %s\n", p);

    return 0;
}

char *strCopy(char *s1, const char *s2)
{

   char *b = s1;

   while (*s2!='\0')
   {
      *s1 = *s2;
      s1++;
      s2++;
   }    
  *s1 = '\0';

  return b;

}


char *strString(const char *s1, const char *s2) // returns a string that starts with the characters in *s2. For example: char *strString ("Annie", "nn") should return "nnie".)
{
   char *test;
   char *b = test;  
   while (*s1 != '\0' && *s2 != '\0')
  {

      if (*s1 == *s2)
      {
         *test = *s1;
      }
      s1++;
      s2++;
   }

*test = '\0';      
return b;
}

I'm having trouble figuring out how to return a value in char *strString when constant integers are the only two parameters. 当常量整数是仅有的两个参数时,我很难弄清楚如何在char * strString中返回值。 When I try, the program crashes. 当我尝试时,程序崩溃。 Keep in mind that the parameters, function declarations, and what's inside main() have to be exactly as they're written. 请记住,参数,函数声明以及main()中的内容必须与编写的内容完全相同。 It's code given to me as part of the project. 它是项目中提供给我的代码。 I can only manipulate what goes inside of the functions. 我只能操纵函数内部的内容。 I'm also not permitted to use arrays in any of my functions. 我也不允许在我的任何函数中使用数组。

(The code inside of *strString is obviously not final. I'm just having trouble testing anything while I can't figure out how to return a value.) (* strString内的代码显然不是最终的。我只是在测试任何东西时都遇到麻烦,但是我不知道如何返回值。)

Inside strString you use the uninitialized pointer test : strString内部,您可以使用未初始化的指针test

char *b = test;   // oops

... ...

*test = *s1;      // oops

You could start with: 您可以从以下内容开始:

char *test = NULL;

Then you could update test when you find your substring. 然后,当您找到子字符串时,可以更新test At no stage do you want to write *test = , because you are not modifying either of the input strings, nor are you creating a new string. 在任何时候,您都不想编写*test = ,因为您既不修改输入字符串,也不创建新字符串。 You should be returning a pointer which points into s1 at the point where the substring can be found. 您应该返回一个可以找到子字符串的指向s1的指针。

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

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