How to use a dynamically allocated vector returned from a function in C?

Asked

Viewed 772 times

2

I have a dynamic size vector that was created in a function and need to return it to the main function.

The function that returns is the following:

int* uniao(int *v1, int n1, int *v2, int n2){
    int *v3;
    int i, j = 0;

    //Aloca dinamicamente v3
    v3 = (int*) malloc((n1 + n2) * sizeof(int*));

    //Preenche o vetor com o v1
    for(i = 0; i < n1; i++){
        v3[i] = v1[i];
    }

    //Preenche o vetor com v2
    for(i = n1; i < (n1 + n2); i++){
        v3[i] = v2[j];
        j++;
    }

    return v3;
}

How could I use it in main function?

I was trying to do that:

pAux = uniao(&v1, n1, &v2, n2); //Ponteiro Auxiliar recebe &v3

for(i = 0; i < (n1 + n2); i++){
    printf("\n%i", *pAux[i]);
}

But the application ends up closing before displaying the vector. : v

  • Added the "union function"

  • The error is not in that part of the code.

2 answers

4

Probably the biggest problem is passing as pointer something that already a pointer. So it works:

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

int* uniao(int *v1, int n1, int *v2, int n2) {
    int *v3 = malloc((n1 + n2) * sizeof(int));
    for (int i = 0; i < n1; i++) v3[i] = v1[i];
    for (int i = n1, j = 0; j < n2; i++, j++) v3[i] = v2[j];
    return v3;
}

int main(void) {
    int v1[] = { 1, 2, 3 };
    int v2[] = { 4, 5, 6 };
    int *pAux = uniao(v1, 3, v2, 3);
    for (int i = 0; i < 6; i++) {
        printf("%d\n", pAux[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

One thing to think about. Who will do the memory release? In this case it is leaking. The main()? But he didn’t, because he should be responsible for it? The basic philosophy of C is: allocated, liberates. How can you not do this within uniao, because dynamic allocation is just to keep the object alive after it, would have to do in function main() and pass the allocated pointer as parameter. Doing this all makes it easier.

  • That’s what I would do in this case (maybe not in another example that was used elsewhere).

  • All malloc() asks for a free()!

  • @Lacobus I think here it was purposeful to leave so to symbolize the memory leaked

0


Your program is "closing" before displaying the result as it is causing a segmentation failure. This error occurs when a program attempts to access (read or write) an address in memory that is reserved for another program.

When using the * (asterisk), also known as operador de dereferência on the line:

printf("\n%i", *pAux[i]);

Are you trying to access the memory address contained in pAux[i], that in your case, it is the integer value contained in one of the elements of your dynamic buffer pointed by pAux, which is certainly not a valid memory address.

No need to use a operador de dereferência in that case, and the right thing would be:

printf("\n%i", pAux[i]);

Or else, if you really like to use the operador de dereferência, combined with a aritmética de ponteiros simple, you can do something like:

printf("\n%i", *(pAux + i));

Follows a corrected and improved version of your program:

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

/* Calcula tamanho de um vetor estatico */
#define sizeofvec(a)   (sizeof(a)/sizeof(a[0]))

int * uniao( int * v1, int n1, int * v2, int n2 )
{
    int i = 0;

    /* Aloca dinamicamente v3 */
    int *v3 = malloc((n1 + n2) * sizeof(int));

    /* Preenche o vetor com o v1 */
    for( i = 0; i < n1; i++)
        v3[i] = v1[i];

    /* Preenche o vetor com v2 */
    for( i = 0; i < n2; i++ )
        v3[n1 + i] = v2[i];

    /* Retorna uniao dos vetores */
    return v3;
}

int main(void)
{
    unsigned int i = 0;

    int v1[] = { 1, 2, 3 };
    int v2[] = { 4, 5, 6, 7, 8 };

    int * pAux = uniao( v1, sizeofvec(v1), v2, sizeofvec(v2) );

    for( i = 0; i < (sizeofvec(v1) + sizeofvec(v2)); i++)
        printf("%d ", *(pAux + i));
    printf("\n");

    free(pAux);

    return 0;
}

Exit:

1 2 3 4 5 6 7 8

If you want to go a little further, follow another version of the same program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Calcula tamanho de um vetor estatico */
#define sizeofarr(a)   (sizeof(a)/sizeof(a[0]))

void uniao( int **v3, int *n3, int *v1, int n1, int *v2, int n2 )
{
    /* Calcula tamanho de v3 */
    *n3 = n1 + n2;

    /* Aloca dinamicamente v3 */
    *v3 = malloc( (*n3) * sizeof(int) );

    /* Preenche o vetor com o v1 */
    memcpy( *v3,  v1, sizeof(int) * n1 );

    /* Preenche o vetor com v2 */
    memcpy( (*v3) + n1, v2, sizeof(int) * n2 );
}

int main(void)
{
    int i = 0;
    int n = 0;
    int * pAux = NULL;

    int v1[] = { 1, 2, 3 };
    int v2[] = { 4, 5, 6, 7, 8 };

    /* Ponteiro Auxiliar recebe v3 */
    uniao( &pAux, &n, v1, sizeofarr(v1), v2, sizeofarr(v2) );

    /* Exibe vetor */
    for( i = 0; i < n; i++)
        printf("%d ", pAux[i]);
    printf("\n");

    /* Libera memoria dinamicamente alocada */
    free(pAux);

    return 0;
}

Exit:

1 2 3 4 5 6 7 8

Browser other questions tagged

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