c - 为什么会有无限循环?

标签 c printf infinite-loop

程序陷入死循环。但是 arr->count printf 打印出一个正常值(例如 4)。 count 的类型是 unsigned intarr 是一个指向 int 的指针。这里有什么问题? loop 先打印 arr 值,然后继续打印 trash 值

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

最佳答案

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

#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

关于c - 为什么会有无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043605/

相关文章:

c - 查找某个范围内的所有良序数字,如何在 C 中 while 循环停止之前打印最后一个值并每行仅打印 10 个值?

Java system.out.format 想要 Object[] 数组而不是简单的变量?

c++ - 在 linux 上使用 c++ 中的键退出无限循环

c++ - 在 C++ 中下载文件时做一个无限循环?

c - HAL_Delay() 陷入死循环

c - 为什么插入函数总是追加在链表的末尾?

C 线程格式化

c++ - 使用 gcc 编译时区分大小写导致错误

c++ - %05d 与 std::stringstream 等价于负数?

python - 是否可以从 C 程序调用 python 方法?