I was doing a dynamic array, but I have a little problem, I'm sure it's simple but I'm not able to see it. I enter the dimension of elements that I want and I enter the number of elements according to that dimension, but when viewing it it doesn't
Code:
//Prototipos de funciones
void introducirDatos(int cantidad,int *x);
void visualizarDatos(int cantidad,int *x);
int main()
{
int cantidad,*x;
introducirDatos(cantidad,x);
visualizarDatos(cantidad,x);
return 0;
}
void introducirDatos(int cantidad,int *x)
{
printf("Introduce la cantidad de elementos del arreglo: ");
scanf("%d",&cantidad);
x = (int*)malloc(sizeof(int));
if(x==NULL)
{
printf("No se a podido reservar memoria");
}
else
{
for(int i=0;i<cantidad;i++)
{
printf("Dato: ");
scanf("%d",&x[i]);
}
}
}
void visualizarDatos(int cantidad,int *x)
{
for(int i=0;i<cantidad;i++)
{
printf("%d ",x[i]);
}
free(x);
}
For this function:
x
is a simple pointer, that is, what is pointed to byx
may be visible outside the function... but changes inx
are local changes. An easier example to see:What value does the program print?
The answer is simple, 0, because
func
it makes local changes. Well, the same thing happens to a pointer:The example is exactly the same... the pointer
a
has not seen its memory address changed. Changes infunc
are local.How to fix this problem? Increasing the level of indirection. If to modify a variable inside a function we need to pass a pointer instead of the variable by value...
... to reassign a single pointer we need the function to receive a double pointer:
And to reassign a double pointer? Then we will need a triple pointer and so on to infinity.