Use generated data in a function

Asked

Viewed 42 times

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, but this identifier will need to be used in other functions. This identification should be returned if the memory space is correctly allocated (where Return 1 is, it should be the "identifier" return). How to do something like this, starting at 0 and being able to be used in other functions?

int criar(){
int *p;

p = malloc(50*sizeof(int));
if(p!=NULL)
    return 1;
else
    return -1;
}
  • Should each allocated memory space have an "id"? What will be returned and used in other functions is this "id"? There is the possibility that you will further detail your problem?

  • They need to be identified in order to be operated on later, for example, in a function that unites two sets. I thought about the use of static variables from yesterday to today, I’ll test and then I’ll give feedback :)

  • A heterogeneous structure does not help?

1 answer

1


You can use the memory address itself as the identifier.

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

However, the way this is, it doesn’t seem like a good idea, because this function allocates a memory and then forgets it, resulting in a memory Leak. Best you return your own pointer:

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

void destruir(int *ponteiro) {
    free(ponteiro);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.