Error assigning malloc to an integer in C language

Asked

Viewed 37 times

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)

  • Ready, Edited.

  • 1

    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));

  • Thank you. I’ll test.

1 answer

1


malloc.cpp: In function 'int main()':
malloc.cpp:39:20: error: invalid conversion from 'void*' to 'int*' [- 
fpermissive]
numeros = malloc(n * sizeof(int));

The error may be from the tutorial or your: depends on who called the file malloc.cpp.

This extension is assumed for C++ programs. In C++ malloc() can be used, but new would be the normal substitute.

Use .c for your C programs. There is a compiler option also --- search in the documentation -- to define which language and use any extension.

In C++ these implicit conversions are prohibited, starting from the idea that any implicit conversion is a certain risk. C++ does not accept. But the C++ compiler compiles C and there’s the (your) problem.

malloc() returns void*. You stated numeros as int* and so has implied a conversion, exactly what the compiler is saying.

Declare

    int*    numero = (int*) malloc(n * sizeof(int));

Prefer the singular, since you will end up writing numero[i] for example :) and is better read than numeros[i]. And declare int* coisa and not int *coisa, why are you declaring coisa after all. And that’s what the compiler will say: what kind of coisa? int*. You declare a name.

  • Thank you. I’ll test.

Browser other questions tagged

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