How to allocate space in memory? [closed]

0

Make a program to allocate space in memory for 10 integers and ask the user to enter 10 values. Then print out their memory address and content.

What do I have to change in my program so that it works?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, *p;

    p = (int*)malloc(10*sizeof(int));

    if (!p);
    {

        printf("Nao foi possivel alocar o vetor !");
        exit(0);

    }


    for(i=0; i<10; i++)
    {

        printf("Digite um valor: ");
        scanf("%d", &p[i]);


    }


    for(i=0; i<10; i++)
    {

        printf("Endereço de memoria: %d\nConteudo: %d\n", &p[i], p[i]);

    }


    free(p);

    return 0;
}
    
asked by anonymous 30.11.2018 / 22:31

1 answer

4

The problem that causes your program to show nothing on the console is% lost, and more in the wrong place:

if (!p);
//     ^--este
{
    printf("Nao foi possivel alocar o vetor !");
    exit(0);

This is a very common error for beginners and it happens that the compiler does not usually say much, but interprets the code differently. In the case of ; causes ; to end there, and so the next code block within if always executes and has {} the program always ends there.

Then to print memory addresses you must use the format exit(0); instead of %p :

printf("Endereço de memoria: %d\nConteudo: %d\n", &p[i], p[i]);
//                            ^--deve ser %p

See the code in Ideone working with these two fixed bugs

    
30.11.2018 / 23:03