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
Added the "union function"
– iojoaomarcos
The error is not in that part of the code.
– Marcelo Junior