Use data generated in a function

0

Hello! The function below aims, whenever called, to allocate a memory space that will serve as a "set" for future uses. These sets must be identified by a number, starting at 0 for the first set and so on, however, that identifier needs to be used in other functions. This ID should be returned if the memory space is allocated correctly (there where return 1 is, it should be the return "identifier"). How to do something like this, starting at 0 and can be used in other functions?

int criar(){
int *p;

p = malloc(50*sizeof(int));
if(p!=NULL)
    return 1;
else
    return -1;
}
    
asked by anonymous 21.10.2015 / 05:12

1 answer

1

You can use the memory address itself as an identifier.

int criar() {
    int *p = malloc(50 * sizeof(int));
    if (p != NULL)
        return (int) p;
    else
        return -1;
}

However, as it is, it does not seem to be a good idea, as this function allocates a memory and then forgets it, resulting in a memory leak . It is best that you return the pointer itself:

int* criar() {
    return malloc(50 * sizeof(int));
}

void destruir(int *ponteiro) {
    free(ponteiro);
}
    
21.10.2015 / 16:48