Guldberg
Guldberg

Reputation: 23

Printing out dynamically allocated memory in C

I'm a total beginner in programming and got an assignment about dynamically allocated memory. One of the expected outputs was a printf statement where all the entered inputs(integers) are printed in a single line, in a row. I have managed to printf in a for-loop, but thats not enought. How do I printf them in a single code-line? Here's the code:

int main()
{ 
    int how_many_integers, count, entered_integers, i, *pSize;

    printf("\nHow many integers are you going to type?\n");
    scanf("%i", &how_many_integers);
    getchar();

    // Allocates memory for the integers.
    pSize = malloc (how_many_integers * sizeof(int));

    // Checks if the integer is 0, and/or reads in all the integers.
    if (how_many_integers == 0)
    {
        printf("No numbers were given.\n");
        exit(0);
    }
    printf("Please enter your integers.\n");
    for (int i = 0; i < how_many_integers; i++)
    {
        scanf("%i", &entered_integers);
        count++;
        pSize[i] = entered_integers;
    }
    for (int i = 0; i < how_many_integers; i++)
    {
        printf("Number: %i\n", *(pSize+i));
    }
    free(pSize);

    printf("Count: %i", count);

    return 0;
}

Upvotes: 0

Views: 2068

Answers (1)

Philipp
Philipp

Reputation: 2516

Try this:

printf("Numbers:");
for (int i = 0; i < how_many_integers; i++)
{
    printf(" %i", *(pSize+i)); // No \n
}
printf("\n"); // if you want a new line at the end

This should result in an output like

Numbers: 1 2 3 4 5

And as others mentioned, your count variable is never initialized. Initialize it to 0.

Upvotes: 4

Related Questions