指针操作期间的Seg Fault

kan*_*008 0 c malloc struct pointers segmentation-fault

我在C中有以下结构.

struct a {
    long state;
    long uid;
    long w, x, y, z, xx, yy, zz, xxx, yyy, zzz;
    char comm[64];
};
Run Code Online (Sandbox Code Playgroud)

然后我做了malloc如下.

buf = malloc (100 * sizeof(struct a));
Run Code Online (Sandbox Code Playgroud)

但是当我尝试按如下方式访问各个结构时,我得到一个seg错误.

for (i = 0; i < 100; ++i) {
    tmp = buf + (i * sizeof(struct a));
    printf ("\t>%d>%ld,%ld\n", i, tmp->state, tmp->uid);
}
Run Code Online (Sandbox Code Playgroud)

我在前10个条目后得到一个段错误.我不知道为什么会这样.请帮忙.

Jos*_*itt 5

如果buf是指向结构a的指针,则指针数学应为:

tmp = buf + i;
Run Code Online (Sandbox Code Playgroud)