简体   繁体   中英

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. 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. 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.)

Inside strString you use the uninitialized pointer 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. 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. You should be returning a pointer which points into s1 at the point where the substring can be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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