c - 将 malloc 用于结构 block

标签 c arrays list linked-list malloc

我正在尝试分配一个内存块,并存储一个结构列表,而无需为每个结构使用多个 mallocs...这只是一个通用示例,我没有之前使用的原始代码,但是这是一般的想法,但我的问题是当我的代码的其他部分在 InitPoints() 函数调用之后执行时,我得到了堆损坏。我不知道我的代码的哪一部分是非法的,但我怀疑它在 InitPoints() 函数的 for 循环中。我正在尝试将其用作表,然后如果内存不足,我可以创建额外的定义大小的表并将它们链接在一起……如果有任何意义的话,有点像动态扩展数组。

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;
} 

最佳答案

这是错误的:

mypoints = mypoints + sizeof(POINT); 

你应该复习一下 C 中的指针算法。只需使用:

mypoints += 1; /* or something similar */

(你的InitPoints函数也有类似的问题)

这是一个引用:

http://www.eskimo.com/~scs/cclass/notes/sx10b.html

关于c - 将 malloc 用于结构 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106828/

相关文章:

具有某些规范的 C++ 数组排序

JavaScript 不重置循环中的变量

list - 将数字拆分为 Prolog 中的数字列表

Python:从文本文件读取的打印行之间的空间太大

python - python 中不需要的列表分配行为

c++ - OpenMP 循环中的索引是否按升序处理?

c - 如何将结构复合文字作为参数传递给函数?

java - 我怎样才能得到一个按钮的数组#/使这个运行更有效

c - 通过套接字发送整数和字符

c - 如何从客户端向服务器发送无效密码?