-1

我有一个定义为的结构

struct new{
  int x;
  int y;
  unsigned char *array;
};

我希望数组是一个根据用户输入动态初始化的数组。内部主要功能:

struct new *sbi;
sbi->array = (unsigned char*)malloc(16 * sizeof(unsigned char));

      for(i=0; i<16; i++)
        {
          sbi->array[i] = 0;
        }

      for(i=0; i<16; i++)
        printf("Data in array = %u\n", (unsigned int)sbi->array[i]);

我确定我对 malloc 做错了什么,但我没有得到它 - 它只是不断给出分段错误。

4

1 回答 1

2

您将 sbi 声明为指向 struct new 的指针,但从不为其分配内存。尝试这个:

struct new *sbi;
sbi = malloc(sizeof(struct new));

另外,不要强制转换 malloc 的结果,因为这会掩盖其他错误,并且不要忘记检查 malloc 的返回值。

于 2015-06-29T21:04:52.367 回答