无法从C

时间:2016-04-17 19:19:18

标签: c printf structure

我想用"数字"制作一个dinamically矩阵。结构元素。当我尝试打印" theNumber"该程序不会退出printf函数。它一直向printf提供零。也许我做错了配置?好吗,请问?

struct number {
    int theNumber;
};

struct table {
    struct number ** mem;
};

unsigned i;

struct table *createInstance(unsigned min) {

//flag1
    struct table * someInstance = (struct table *) malloc(sizeof (struct table));

//flag2
    if (someInstannce == NULL) {
        return 0;
    }

//flag3
    someInstannce->mem = (struct number **) malloc((min + 1) * sizeof (struct number **));

//flag4
    for (i = 0; i <= min; i++) {
        someInstannce->mem[i] = (struct table *) calloc(5, sizeof (struct number *) + 1);
    }

//flag5
    for (i = 0; i <= min; i++) {
        for (j = 0; j = 5; j++) {
            printf("%d", someInstannce->mem[i][j].theNumber);
        }
    }

    return someInstance;
}

2 个答案:

答案 0 :(得分:0)

这一行

for (j = 0; j = 5; j++)

会将j限制为5,条件测试将为“true”,因为5为非0。循环永远不会结束。尝试

for (j = 0; j < 5; j++)

我也提问

someInstannce->mem[i] = (struct table *) calloc(5, sizeof (struct number *) + 1);

您转换为其他类型,并请求指针大小,而不是结构大小。分配应该

someInstance->mem[i] = calloc(5, sizeof (struct number) + 1);

答案 1 :(得分:0)

你应该为任何指针分配内存,指针的某种类型的内容,例如,int * i = malloc(sizeof(int));

请编辑

 someInstannce->mem = (struct number **) malloc((min + 1) * sizeof (struct number **));

 someInstannce->mem = (struct number **) malloc((min + 1) * sizeof (struct number *));

 someInstannce->mem[i] = (struct table *) calloc(5, sizeof (struct number *) + 1);

 someInstannce->mem[i] = (struct number *) calloc(5, sizeof (struct number) + 1);

打印循环状况不佳,j = 5应为j <5。