0
Hello
I’m following a tutorial on Youtube about dynamic memory allocation in c language, but I’m getting an error regarding the attribution of a malloc() to an integer type variable. The strange thing is that in the tutorial does not give this error, because only I am getting this error ?
The error is on this line:
numeros = malloc(n * sizeof(int));
Error:
malloc.cpp: In function 'int main()':
malloc.cpp:39:20: error: invalid conversion from 'void*' to 'int*' [-
fpermissive]
numeros = malloc(n * sizeof(int));
~~~~~~^~~~~~~~~~~~~~~~~
My code:
#include<stdio.h>
#include<stdlib.h>
int main ()
{
// Variáveis de teste de ponteiros
int *numeros;
int n;
printf("Quantidade de numeros:");
scanf("%d",&n);
numeros = malloc(n * sizeof(int));
for(int i = 0; i < n; i++)
{
printf("Numero %d: ", i);
scanf("%d",&numeros[i]);
}
printf("Numeros lidos: ");
for(int i = 0; i < n; i++)
{
printf("%d", numeros[i]);
}
printf("\n");
return 0;
}
Thank you
What error is your compiler accusing? (If you can edit and include in the question, it would help a lot)
– Naslausky
Ready, Edited.
– user1950241
Oh yes. It depends on the compiler you are using. Is there any reason for you to save your file with ending
.cpp
? It should just be.c
..cpp
is for C++. Anyway, try putting a Typecast in front:numeros = (int *)malloc(n * sizeof(int));
– Naslausky
Thank you. I’ll test.
– user1950241