How to allocate memory space?

Asked

Viewed 132 times

0

Make a program to allocate memory space for 10 integers and ask the user to enter 10 values. Later, print your respective memory address and content.

What I have to change in my program to make it work ?

#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;
}

1 answer

4

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

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

This is a very common bug for beginners and it turns out that the compiler doesn’t usually say much, but interprets the code differently. In case the ; causes the if ends there, and so the next code block within {} always executes and as has a exit(0); the program always ends there.

Then to print memory addresses must use the formatter %p instead of %d:

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

See the code on Ideone working with these two fixed bugs

Browser other questions tagged

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