开发者

Returning a String from function in C

开发者 https://www.devze.com 2023-04-05 04:42 出处:网络
char* clean_string (char *input_string){ /*Ensure that input string isn\'t null and only do heavy lifting if it\'s not null*/
char* clean_string (char *input_string){
  /*Ensure that input string isn't null and only do heavy lifting if it's not null*/
  if (input_string){
    char *stripped;
    stripped = (char*)malloc(strlen(input_string)*sizeof(char));
    while (*input_string != '\0'){
      if isalpha(*input_string){
        *stripped = toupper(*input_string);
    input_string++;
    stripped++;
      } else {
        input_string++;
    }
  }
/*       *stripped++ += '\0';*/
   return stripped;
  }
 /*default return val*/  
return NULL;
}

Can anybody tell me where I'm going wrong with this? Trie开发者_Python百科d to do a test run and it doesn't output anything when I try to call it.


You are returning a pointer to the last character in the string (stripped++ ?).
You are allocating one byte too few (should be strlen(...) + 1).

stripped = (char*)malloc(strlen(input_string)*sizeof(char)); /* Wrong. */
stripped = (char*)malloc(strlen(input_string) + 1);

/* .. */
stripped++;

/* .. */
return stripped;

Try to keep a copy, something like original_stripped = stripped before starting to change stripped, and return the copied value (not the incremented one).


The problem is with calling stripped++. You are modifying the pointer you get by malloc. Make an extra pointer char *result_char = stripped; and use that for iteration over resulting string.


The problem ís that you increment your stripped variable before returning it. Try:

char *stripped; 
char *result;
stripped = (char*)malloc(strlen(input_string)*sizeof(char)); 
result = stripped;
...
return result; 


How about just:

    char* clean_string (char *input_string)
    {
      /*Ensure that input string isn't null and only do heavy lifting if it's not null*/
        if (input_string)
        {
            char *stripped;
            int i;

            stripped = (char*)malloc(strlen(input_string)*sizeof(char) + 1);

            for(i=0; i < strlen(input_string); i++)
                stripped[i] = (isalpha(input_string[i]) ? toupper(input_string[i]) : input_string[i]);

            return stripped;
        }
     /*default return val*/  


return NULL;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消