开发者

using functions in c (return value)

Learning C and having many doubts.

I have a function (lets say function 1) that calls another function (lets say function 2). Function 2 calculates an array of string.

How can I use this array in function 1?

Some code example:

  int find_errors(char* word)
    {
        char error[100];

        /*Given the word, It will find the duplicate chars and store it in the
        error array. */



       return 0;
    }
  int find_word(char* word)
    {

        find_errors (开发者_如何学JAVAword);

        printf("%s\n", error);

        return 0;
    }


There are at least three possible approaches:

  1. Use a global variable
  2. pass a parameter between them
  3. return a pointer from the function


There are multiple ways to do this.

1) Create a dynamic array and return a pointer to the array. This will require you to manually free the memory for the array at a later time.

#define NUM_ELEMS 50

// In find_error():
char* error = malloc(NUM_ELEMS * sizeof(char));
return error;

// In find_word():
char *error = find_errors();
// do stuff
free(error);

2) Pass a pointer to find_errors that it can use as the error array. This will not require you to manually free the memory.

// In find_word():
char error[NUM_ELEMS];
find_error(error);

3) Use a global array. May make it more difficult for other people to understand your code. Has other potential problems as well.

// In global scope:
char error[NUM_ELEMS];


Your question relates to "call-by-reference" and "call-by-value".

char* getNewValsToSet(void)
{
  char* new_vals = (char*) malloc(sizeof(char[5]));
  new_vals[4] = '\0';
  return new_vals;
}

void setValuesEven(char* vals_to_set)
{
  vals_to_set[0] = 'A';
  vals_to_set[2] = 'C';
}

void setValuesOdd(char* vals_to_set)
{
  vals_to_set[1] = 'B';
  vals_to_set[3] = 'D';
}

int main(void)
{
  char* some_vals_to_set = getNewValsToSet();
  setValsEven(some_vals_to_set);
  setValsOdd(some_vals_to_set);

  // ... now has vals "ABCD"

  free(some_vals_to_set);  //cleanup

  return 0;
}

If you have "doubts" about learning C, IMHO it's one of the best things you can do (no matter the language in which you work) because it will explain exactly how things work "under-the-hood" (which all high-level languages try to hide to some degree).


You need to declare the error array globally and use it just like you did.

EDIT: using global variables isn't the best practice in most of the cases, like this one.


Here is an example of what you are looking for with an awesome console output. It dynamically allocates the array to hold any number errors (duplicate characters in your case) that may occur.

//Only free errors if result is > 0
int find_errors(char* word, char** errors)
{
    int num_errors = 0;
    int word_length = strlen(word);
    int ARRAY_SIZE = MIN(8, word_length);
    char existing[word_length];
    int existing_index = 0;

    *errors = NULL;

    for(int i = 0; i < word_length; i++)
    {
        char character = word[i];

        //Search array
        for (int n = 0; n < word_length; ++n ) {
            if(n >= existing_index)
            {
                existing[n] = character;
                existing_index++;
                break;
            }
            if (existing[n] == character) {
                num_errors++;

                if(!*errors)
                    *errors = (char*)malloc(ARRAY_SIZE * sizeof(char));

                //Check if we need to resize array
                if(num_errors >= ARRAY_SIZE)
                {
                    ARRAY_SIZE *= 2;
                    ARRAY_SIZE = MIN(ARRAY_SIZE, word_length);

                    char *tmp = (char*)malloc(ARRAY_SIZE * sizeof(char));
                    memcpy(tmp, *errors, (unsigned long)ARRAY_SIZE);
                    free(*errors);
                    *errors = tmp;
                }
                //Set the error character
                (*errors)[num_errors - 1] = character;
                break;
            } 
        } 
    }

    return num_errors;
}
int find_word(char* word)
{
    char* errors;
    int errCount = find_errors (word, &errors);
    if(errCount > 0)
    {
        printf("Invalid Characters: ");
        for(int i =0; i < errCount; i++)
        {
            printf("%c ", errors[i]);
        }
        printf("\n");

        free(errors);
    }

    return 0;
}

int main(int argc, char *argv[])
{
    find_word("YWPEIT");
    find_word("Hello World");
    find_word("XxxxXXxXXoooooooOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOooooooOOO");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜