malloc指向结构的指针指针成员

时间:2015-05-11 05:44:43

标签: c pointers struct malloc dynamic-memory-allocation

我正在尝试使用一个结构来保存指向数据块的指针,我有时会在更新文件时更改,这个想法是释放旧数据块,malloc是正确大小的新数据块,并分配结构中指针指向malloc返回的指针,这就是我认为我应该这样做的。但它会出错。事实上,在我制作这个测试程序的较大程序中,它不是段错误,但写入stdout后没有做任何事情(在程序之后的任何地方)。我想我正在写stdout FD,原因是当我将指针设置为$('.popInfoHG').click(function () { var ListID = $(this).parent().find('[id*=hidlid]').val(); $.post("redir.aspx", { lid: ListID }); }); ed返回值时,我正在错误地使用指针。

malloc()

为方便起见,我想最初在#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <malloc.h> #include <inttypes.h> struct mystruct { int offset; int ** d; }; int filecheck (struct mystruct *g, int * count) { int v, size = 0; FILE *f = fopen("/home/pi/schedule/default", "rb"); if (f == NULL) { return 0; } fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); int schedsize = sizeof(int); int elementcount = size / schedsize; // free(*(g->d)); // seg fault next line if ((*(g->d) = malloc(size))==NULL) return 0; if (elementcount != fread(*(g->d), schedsize, elementcount, f)) { free(*(g->d)); return 0; } fclose(f); *count = elementcount; return 1; } void setp (struct mystruct *g) { // if uncommented, seg fault here // *(g->d) = NULL; } int main (){ struct mystruct g; setp(&g); int i, count = 0; if (filecheck(&g, &count)==0) { printf("Returned 0\n"); return 0; } while (1) { printf("%d\n", (*(g.d))[i]); sleep(1); } return 0; } 中将mystruct.d设置为NULL,但即使这些内容仍未完成,因此我知道它完全错误。也许我不需要使用指针指针,但在我看来,我做到了。

编辑:根据答案修改,这可以吗?

setp()

这似乎有效但是它是正确的还是我在写一些记忆的部分我不应该再用这个了?

1 个答案:

答案 0 :(得分:2)

在使用之前,您需要为所有指针元素分配内存。

这里,d是指向指针的指针,首先你需要为d本身分配内存,然后你应继续取消引用d(使用*d

例如,

void setp (struct mystruct *g) { 

 g->d = NULL;   // no need to derererence d here, but later need to allocate
}

或,( for better

void setp (struct mystruct *g) {

 g->d = malloc(32 * sizeof (int *));  // d is allocated
 g->d[i] = malloc(16 * sizeof (int));   // or g->d[i] = NULL; or *(g->d) = NULL;
}

应该可以正常工作。

此外,main()的推荐信息为int main(void)