Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make my function return a dynamic array?

So at the moment I have a function I made returning a static array, is there any way to make it return a dynamic array for the sake of efficiency?

#include <stdio.h>
#include <stdlib.h>
#include "header.h"

int *charpos(char *str, char ch)
{
    int *bff, bc, ec, i, strln;
    static int ret[255];
    bc = 0;
    ec = 0;

    for(i = 0; str[i] != '\0'; i++)
        ;

    strln = i;
    for(i = 0; i <= strln; i++)
    {
        if(str[i] == ch)
            ec++;
    }

    bff = malloc(sizeof(int)*ec);
    if(sizeof(bff) > sizeof(ret))
    {
        free(bff);
        return 0;
    }

    for(i = 0; i <= 255; i++) ret[i] = '\0';
    for(i = 0; i <= strln; i++)
    {
        if(str[i] == ch)
        {
            ret[bc] = i;
            bc++;
        }
    }

    free(bff);
    return ret;
}
like image 734
Keith Miller Avatar asked Jul 31 '12 22:07

Keith Miller


1 Answers

Functions cannot return arrays, period. You can of course a pointer or take a pointer to a block of memory that has been allocated by the caller. So, in your case...

int *ret = malloc(255 * sizeof int);  // caller must deallocate!

This does change the semantics of your code however. The caller of your function is now responsible for calling free() on the returned pointer. If they do not you will leak memory, so this adds some amount of complexity that did not exist before. I would prefer something like this instead:

void charpos(int *p, size_t size, const char *str, char ch) {
    // initialize the memory 
    memset(p, 0, size * sizeof int);
    
    // your other code here...

    size_t len = strlen(str);
    // fill the caller's memory
    for(i = 0; i < len; ++i)
    {
        if(str[i] == ch)
            p[bc++] = i;
    }
}

You're returning a pointer to int which referes to the first element of a statically allocated array.

like image 189
Ed S. Avatar answered Oct 19 '22 17:10

Ed S.