Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this C for-loop not working properly?

int main()
{
    int t, i;
    int *nums;
    scanf("%d", &t);
    nums = malloc(t * sizeof(int));
    for(i = 0; i < t; i++)
    {
        scanf("%d", &nums[i]);          
    }
    printf("hey");
}

For some reason, it hangs, waiting for more input! Any ideas?

like image 669
Antoni4040 Avatar asked Jan 31 '26 01:01

Antoni4040


1 Answers

This code is correct, except for the fact that you're not freeing your memory (not a big issue for this simple code) and you're not checking scanf for errors, which may be the cause of your problem.

A better implementation with error checking and correct memory handling is described below:

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

int main()
{
    int t, i, ret;
    int *nums;

    ret = scanf("%d", &t);          
    if(ret != 1)
    {
        /* something wrong */
    }

    nums = malloc(t * sizeof(int));
    if(nums==NULL)
    {
        /* memory error */
    }

    for(i = 0; i < t; i++)
    {
        ret = scanf("%d", &nums[i]);          
        if(ret != 1)
        {
            /* something wrong */
        }

    }
    free(nums);
    printf("hey");

    return 0;
}
like image 105
Tarantula Avatar answered Feb 01 '26 17:02

Tarantula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!