简体   繁体   English

C中的calloc结构

[英]calloc struct in C

I'm trying to initialize a pointer to a struct with 0.0 values in there. 我正在尝试初始化一个指向结构的指针,其中包含0.0值。 Look at the following situation: 看看以下情况:

typedef struct 
{
    float a;
    float b;
    float c;
} structA;

structA *ptr = calloc(100000, sizeof(structA));

I want all the values in *ptr be structA with initial values of {0.0, 0.0, 0.0}, but this is not I have now. 我希望* ptr中的所有值都是structA,初始值为{0.0,0.0,0.0},但这不是我现在所拥有的。 Many of the indices of *ptr appear correctly, but some indices appear with weird values (like {0.0, 0.0, 10241256124.0}). * ptr的许多索引正确显示,但某些索引显示奇怪的值(如{0.0,0.0,10241256124.0})。

If I try malloc, the same thing happens. 如果我尝试malloc,就会发生同样的事情。

What should I do? 我该怎么办?

You're doing something wrong... I've never used objective-c, so I stuck the code below into ideone.com and it worked as expected... (printing out done, not failed because) all values were zero'd. 你做错了什么......我从来没有使用过objective-c,所以我将下面的代码插入到ideone.com中 ,它按预期运行...(打印完成,没有失败,因为所有值都为零) d。 My guess is you're not checking properly, since it's quite unlikely there's a bug in your compiler... 我的猜测是你没有正确检查,因为你的编译器中不太可能存在错误......

#include <malloc.h>

typedef struct 
{
    float a;
        float b;
        float c;
} structA;



int main() {
    int count = 100000;
    int i;
    structA *ptr = calloc(count, sizeof(structA));
    if(ptr) {
        for(i=0;i<count;i++) {
            if(ptr[i].a || ptr[i].b || ptr[i].c) {
                printf("fail\n");
            }
        }
        printf("done\n");
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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