为什么有一个无限的循环?

时间:2013-11-18 08:54:58

标签: c printf infinite-loop

程序属于无限循环。但是arr->count printf会打印一个正常值(例如4)。 count的类型为unsigned intarr是指向int的指针。这有什么问题? loop首先打印arr值,然后继续打印垃圾值

arrat_get中,它打印数组就好了

struct _arr {
    size_t count;
    int* arr;
} ;

typedef struct _arr array_t;


array_t* array_get(FILE* file){
    int* arr = NULL;
    size_t count = 0;
    array_t* arr_t;
    array_t temp;
    int i = 0;

    if (!file) {
        fprintf(stderr, "there is no such file\n");
        return;
    }



    if (fscanf(file, "%u", &count) == EOF) {
        fprintf(stderr, "can't read count from file\n");
        return;
    }

    temp = array_create(arr, count);
    arr_t = &temp;

    printf("%i\n", arr_t->count);


    for (i = 0; i < arr_t->count; i++){
        if (fscanf(file, "%d", &arr_t->arr[i]) == EOF) {
            fprintf(stderr, "can't read arr from file\n");
            return;
        }
    }

    for (i = 0; i<arr_t->count; i++)
        printf("%d ", arr_t->arr[i]);
    printf("\n");

    return arr_t;
}


int main(){
   array_t* arr_t;
   int i = 0;


   printf("enter count and arr:\n");
   arr_t = array_get(stdin);

   printf("count in main=%u\n", arr_t->count);
   for (i = 0; i<arr_t->count; i++)
       printf("%d ", arr_t->arr[i]);



   getch();

   return 0;
}

1 个答案:

答案 0 :(得分:0)

这不是您问题的解决方案,但可以帮助您找到它:

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

struct _arr {
    int count;
    int* arr;
} ;


int main(){
    int i = 0;
    struct _arr myArray[10];

    for (i = 0; i < 10; i++) {
        myArray[i].count = 9;
        myArray[i].arr = &myArray[i].count;
    }


    for (i = 0; i < (myArray->count); i++)
       printf("%d    %p\n", myArray[i].count, myArray[i].arr);


    return 0;
}

输出:

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo 
10 0x7fffeb764c00
10 0x7fffeb764c10
10 0x7fffeb764c20
10 0x7fffeb764c30
10 0x7fffeb764c40
10 0x7fffeb764c50
10 0x7fffeb764c60
10 0x7fffeb764c70
10 0x7fffeb764c80