diz
diz

Reputation: 23

Returning a String from function in C

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? Tried to do a test run and it doesn't output anything when I try to call it.

Upvotes: 2

Views: 347

Answers (4)

Sanjeev
Sanjeev

Reputation: 211

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;
}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

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

Upvotes: 7

stacker
stacker

Reputation: 68942

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; 

Upvotes: 2

Juraj Blaho
Juraj Blaho

Reputation: 13451

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.

Upvotes: 2

Related Questions