Can u help me with this code?

import random

def main():
    # Declara uma variável para armazenar o ponteiro para a matriz
    ptr = None
    
    # Solicita ao usuário o tamanho da matriz
    size = int(input("Digite o tamanho da matriz: "))
    
    # Aloca um bloco de memória para a matriz
    ptr = malloc(size * sizeof(int))

    # Preenche a matriz com números aleatórios
    for i in range(size):
        ptr[i] = random.randint(0, 100)
        
    # Imprime a matriz na tela
    for i in range(size):
        print(ptr[i])
        
    # Libera a memória alocada
    free(ptr)
    
if __name__ == "__main__":
    main()

the errors

Digite o tamanho da matriz: 1
Traceback (most recent call last):
  File "<string>", line 25, in <module>
  File "<string>", line 11, in main
NameError: name 'malloc' is not defined
>>>

You can’t mix Python and C like that.

You don’t need to manage memory manually in Python. Correct Python for what it looks like what you’re trying to do:

import random

for _ in range(int(input("enter a number")))
    print(random.randint(0, 100))

You will also want to replace the following line:

if name == “main”:

With:

if __name__ == '__main__':

Please first read the pinned thread and make sure to fix the code formatting so that we can see it exactly as you actually have it.

Oh, the OP had __name__ etc. But it wasn’t inside code fences so it
got interpreted as markdown, hiding it from your view :slight_smile:

Cheers,
Cameron Simpson cs@cskk.id.au

Comment on the code inline below:

 def main():
     # Declara uma variável para armazenar o ponteiro para a matriz
     ptr = None

You do not need to “declare” variables in Python. You can remove the
line above.

     # Solicita ao usuário o tamanho da matriz
     size = int(input("Digite o tamanho da matriz: "))

     # Aloca um bloco de memória para a matriz
     ptr = malloc(size * sizeof(int))

The NameError you got is literally complaining that the name malloc
is unknown. You haven’t imported it from somewhere or defined it
yourself.

We don’t directly call C’s malloc in Python. The most direct parallel is
probably to make a list of ints of your desired size, like this:

 ptr = [0] * size

Then the rest of your code will basic run normally.

     # Libera a memória alocada
     free(ptr)

Python releases storage for you when all references to an object are
gone. Your ptr reference to the list will vanish when you leave the
main() function, so that will happen automatically.

So there’s no free() function. You can remove this line.

Cheers,
Cameron Simpson cs@cskk.id.au

2 Likes