简体   繁体   中英

for loop does not terminate on false condition

The for loop should iterate only 5 times but first for loop is iterating 6 times but seconds works correctly with same condition.

    int i, j, n = 5;
    int *p;
    printf("enter size of array=");
    scanf("%d", &n);

    p = (int *)calloc(sizeof(int), n);  

    printf("enter array\n");

    for (i = 0; i < n; i++) {
        scanf("%d ", (p + i));
    }

    printf("array\n");

    for (j = 0; j < n; j++) {
        printf("%d ", *(p + j));
    }
    free(p);

The number of iterations of both loops is determined by the first number input at the prompt enter size of array= .

You should be more defensive: reject invalid input and detect errors.

Here is a modified version:

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

int main() {
    int i, n;
    int *p;

    printf("Enter array size: ");
    if (scanf("%d", &n) != 1 || n <= 0) {
        printf("invalid input\n");
        return 1;
    }

    p = (int *)calloc(sizeof(int), n);
    if (p == NULL) {
        printf("allocation failure\n");
        return 1;
    }

    printf("enter array\n");
    for (i = 0; i < n; i++) {
        if (scanf("%d ", (p + i)) != 1) {
            printf("invalid input\n");
            return 1;
        }
    }

    printf("array\n");
    for (i = 0; i < n; i++) {
        printf("%d ", *(p + i));
    }
    printf("\n");
    free(p);
    return 0;
}

hey @harsh you didn't made mistake in pointers point of view. but the problem is cause by scanf.

As you have provided '_' (a blank space)( scanf("%d ", (p + i)) ) after %d ; then scanf will always finds a space(or any spacing character) after a each occurences of provided value and iterates a one more time in search of that hence it will run one more occurence last time.

just remove that space, it'll work. Hopefully this helps.

do

scanf ("%d", (p+i))

ie, do not give space after %d

also syntax of calloc should be

p = (int *)calloc(n, sizeof(int));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM