How can I return a character array from a function in C?

后端 未结 6 1784
醉话见心
醉话见心 2020-11-29 10:11

is that even possible? Let\'s say that I want to return an array of two characters

char arr[2];
arr[0] = \'c\';
arr[1] = \'a\';

from a func

6条回答
  •  猫巷女王i
    2020-11-29 10:55

    You've got several options:

    1) Allocate your array on the heap using malloc(), and return a pointer to it. You'll also need to keep track of the length yourself:

    void give_me_some_chars(char **arr, size_t *arr_len)
    {
        /* This function knows the array will be of length 2 */
        char *result = malloc(2);
    
        if (result) {
            result[0] = 'c';
            result[1] = 'a';
        }
    
        /* Set output parameters */
        *arr = result;
        *arr_len = 2;
    }
    
    void test(void)
    {
        char *ar;
        size_t ar_len;
        int i;
    
        give_me_some_chars(&ar, &ar_len);
    
        if (ar) {
            printf("Array:\n");
            for (i=0; i

    2) Allocate space for the array on the stack of the caller, and let the called function populate it:

    #define ARRAY_LEN(x)    (sizeof(x) / sizeof(x[0]))
    
    /* Returns the number of items populated, or -1 if not enough space */
    int give_me_some_chars(char *arr, int arr_len)
    {
        if (arr_len < 2)
            return -1;
    
        arr[0] = 'c';
        arr[1] = 'a';
    
        return 2;
    }
    
    void test(void)
    {
        char ar[2];
        int num_items;
    
        num_items = give_me_some_chars(ar, ARRAY_LEN(ar));
    
        printf("Array:\n");
        for (i=0; i

    DO NOT TRY TO DO THIS

    char* bad_bad_bad_bad(void)
    {
        char result[2];      /* This is allocated on the stack of this function
                                and is no longer valid after this function returns */
    
        result[0] = 'c';
        result[1] = 'a';
    
        return result;    /* BAD! */
    }
    
    void test(void)
    {
        char *arr = bad_bad_bad_bad();
    
        /* arr is an invalid pointer! */
    }
    

提交回复
热议问题