0

I'm trying to call in a String, add a character based on certain conditions, update the longest String and then return the String.

I know that since I'm changing the String (by adding characters), I can't use const char* pointer, thus I must use a char array[].

But I also know that char array[] can't be returned, just the pointer. So I'm confused on how I can update a String (as a char array[]), and then return it (as a const char* pointer).

 const char* longestWord(char line[])
 {
     int pos = 0;
     char longest[250]; 
     char ch = line[pos];
     int longestLength = 0;
     char current[250];
     int currentLength = 0;

      if(isalpha(ch) || isdigit(ch))
      {
          longest[longestLength] = ch;
          longest[longestLength + 1] = '\0';
          currentLength++;
      }

    pos++;  
 }
 return longest;
9
  • 2
    Does your compiler issue a warning on the return longest line? Commented Jun 3, 2015 at 23:33
  • Why don't you just pass it to the function as a pointer? Commented Jun 3, 2015 at 23:33
  • 2
    Choose between starting with a longer string in your source (so there is room for expansion), or allocating it and passing a pointer to the pointer (so it can be reallocated in the function). Commented Jun 3, 2015 at 23:34
  • @dasblinkenlight, yes it does have a warning: address of stack memory associated with local variable 'longest' returned Commented Jun 3, 2015 at 23:37
  • @kris: Yeah, that means you're returning a local variable which when accessed from the outside, will result in undefined behavior. Commented Jun 3, 2015 at 23:39

2 Answers 2

2

Unless line is large enough to hold as much as it will ever need, you won't be able to do it this way.

Most straightforward solution here would be to have the argument be on the heap, so allocate it with malloc(length_of_str). In longestWord you may then call line = realloc(line, new_length) in order to get yourself more room to stuff characters in.

Returning longest won't ever work as it is on the stack, which will be freed once your method is left. You may allocate longest via malloc() as well and return that pointer, in which case you'll only need to call free() on the returned pointer once you no longer need it.

Sign up to request clarification or add additional context in comments.

Comments

0

Just pass the array to the function and you don't need to return anything:

void longestWord(char line[], char longest[])
                     //       ^^^^^^^^^^^^^^

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.