2

This code finds the next word in the string.

For example

given an input of " my cake" the function should return "my cake". as the expected output

If I use return then the output is (null), but I use printf then the code works

I would like to know how to get the expected output using return.

       #include <stdio.h>
        int main()
        {
        char* str[1000]; 
        printf("enter:");
        fgets(str,1000,stdin);

        printf("%s",find_word_start(str));
        }



        char* find_word_start(char* str){
                char* result[1000];
                int c = 0, d = 0;
                while(str[c] ==' ') { 
                    c++; 
                }
                while(str[c] != '\0'){ 
                    result[d++] = str[c++];

                    if(str[c]==' ') {
                    result[d++] = str[c++]; 
                } 
                while(str[c]==' ') { // 
                    c++; 
                } 
            }
            result[d] = '\0';

            //print or return char?
            return result;
    }
miguel munoz
  • 55
  • 10
  • 4
    Did you perhaps mean `char result[1000]` instead of `char *result[1000]`? Also - `result` is an automatic variable defined on the stack. Returning it from a subroutine is a classic mistake. Suggest: define `result` as `char *`, allocate memory for it dynamically, and return that. Caller is the responsible for cleaning up the allocated memory. – Bob Jarvis - Слава Україні Sep 15 '19 at 01:31
  • You're returning pointer to stack value. Does this even compile? – geckos Sep 15 '19 at 01:34
  • @geckos: that would depend very much on the OS, compiler, and compiler options being used. – Bob Jarvis - Слава Україні Sep 15 '19 at 01:41
  • @BobJarvis I tried `char result[1000]` and still returns null, I do not know how to allocate memory dinamically, I am new to c language. I tried `char* result;` instead of `char* result[1000]` and it works know even though I do not understand why. – miguel munoz Sep 15 '19 at 01:42
  • 1
    `result` is an array of automatic storage duration, so ceases to exist as far as the program is concerned when the function returns. Using it as a return value, and using that return value in the caller, causes undefined behaviour. – Peter Sep 15 '19 at 02:58

2 Answers2

2

char* result[1000]; creates an array of 1000 pointers. That's wrong in a number of ways.

  1. You want a block of 1000 chars, not pointers.
  2. Actually, 1000 is not the number of characters you want. You usually want a smaller number, but you could also want a larger number.
  3. You don't want to store the result in automatically allocated memory, because that will be freed as soon as you exit the function. Use malloc (or something that does a malloc such as strdup).

Fix:

// Returns a copy that needs to be freed.
char* find_word_start(const char* src) {
   while (*src == ' ')
      ++src;

   size_t len = 0;
   while (str[len] != '\0')
      ++len;

   ++len;  // Include NUL
   result = malloc(len);

   char* dst = result;
   while (len--)
      *(dst++) = *(src++);

   return result;
}

Well, I was avoiding using string functions above like you did, but they greatly simplify the solution.

// Returns a copy that needs to be freed.
char* find_word_start(const char* src) {
   while (*src == ' ')
      ++src;

   return strdup(src);
}

That said, since you return the tail end of the string, you could simply return a pointer into the existing string.

// Returns a pointer into the provided string.
const char* find_word_start(const char* str) {
   while (*str == ' ')
      ++str;

   return str;
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

The following line allocates memory space in the stack but after the function ends everything is gone:

char result[1000];

You need to allocate memory in the heap like that:

char *result = malloc(sizeof(char) *1000);

Note: don't forget to free that memory space by free function.

Lion King
  • 32,851
  • 25
  • 81
  • 143