使用malloc对于结构的块 [英] using malloc for block of structs
问题描述
我试图分配的内存块,并存储结构的列表,而无需使用多个mallocs为每...这只是一个普通的例子,我没有原来的code我正在同早些时候,但这是一般的想法,但我的问题是,当我的code的其他部分InitPoints()函数调用之后执行的,我是越来越堆损坏。我不知道我的code的一部分是非法的,但我怀疑这是在为InitPoints环路()函数。我试图用这个作为表,那么我可以创建定义大小的附加表,如果我用完了内存和它们链接在一起......所以有点像一个动态扩展数组,如果让任何意义。
typedef结构{铽
POINT点;
POINT *接下来的;
}表;typedef结构{铂
INT X;
诠释Ÿ;
}点;POINT * mypoints;诠释主(){
INT大小= 10;
INT I = 0;
mypoints = InitPoints(大小); 对于(i = 0; I<大小;我++)
{
的printf(mypoint内容[%d] =(%D,%D)\\ n,我,mypoints-> X,mypoints-> Y);
mypoints = mypoints +的sizeof(POINT);
}
//其他一些code ...
//即的CreateThread(....) 返回0;
}POINT * InitPoints(INT大小)
{
POINT * tmp目录;
POINT *原稿;
INT A = 10;
INT B = 1000;
原稿=(POINT *)malloc的(的sizeof(POINT)*大小);
如果(原稿== NULL)
返回NULL; TMP =原稿;
对于(i = 0; I<大小;我++)
{
tmp-> X = A ++;
tmp-> Y = B ++;
TMP = TMP +的sizeof(POINT);
}
返回原稿;
}
这是错误的:
mypoints = mypoints +的sizeof(POINT);
您应该检查C.指针运算只需使用:
mypoints + = 1; / *或类似的东西* /
(有你InitPoints功能类似的问题)
这里有一个referemce:
http://www.eskimo.com/~scs/cclass/笔记/ sx10b.html
I am trying to allocate a block of memory, and store a list of structures without using multiple mallocs for each... this is just a generic example, I don't have the original code I was working with earlier, but this is the general idea, but my problem was that I was getting heap corruption when other parts of my code executed after the InitPoints() function call. I don't know what part of my code is illegal, but I suspect it is in the for loop of the InitPoints() function. I am trying to use this as table, then I can create additional tables of defined size if I ran out of memory and link them together... so kind of like a dynamic expanding array if that makes any sense.
typedef struct Tb{
POINT points;
POINT *next;
} TABLE;
typedef struct Pt{
int x;
int y;
}POINT;
POINT *mypoints;
int main() {
int size = 10;
int i = 0;
mypoints = InitPoints(size);
for(i=0; i < size; i++)
{
printf("mypoint [%d] = (%d,%d)\n",i, mypoints->x, mypoints->y);
mypoints = mypoints + sizeof(POINT);
}
// some other code...
// i.e. createThread(....)
return 0;
}
POINT* InitPoints(int size)
{
POINT *tmp;
POINT *orig;
int a = 10;
int b = 1000;
orig = (POINT*) malloc (sizeof(POINT) * size);
if(orig == NULL)
return NULL;
tmp = orig;
for (i = 0; i < size; i++)
{
tmp->x = a++;
tmp->y = b++;
tmp = tmp + sizeof(POINT);
}
return orig;
}
This is wrong:
mypoints = mypoints + sizeof(POINT);
You should review pointer arithmetic in C. Just use:
mypoints += 1; /* or something similar */
(There is a similar problem in your InitPoints function)
Here's one referemce:
http://www.eskimo.com/~scs/cclass/notes/sx10b.html
这篇关于使用malloc对于结构的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!