c - C语言中如何分配不同类型的内存?

标签 c arrays pointers struct

我在 C 中有以下代码:

typedef struct
{
   int age;
   int phoneNumber;
} Student;

typedef struct
{
  int id;
  int student[1];
} People;

#define NUM_OF_PEOPLE
void *p = malloc(sizeof(People) + sizeof(int) * NUM_OF_PEOPLE + sizeof(Student) * NUM_OF_PEOPLE);

如何找到指向内存中 struct Student 第一个元素的内存指针?

我尝试通过以下方式做到这一点:

int i = 0;
for(i = 0; i < NUM_OF_PEOPLE; i++)
{
   Student * student_p = p.student[NUM_OF_PEOPLE];
}

不行,那我们可以这样分配内存吗?
那么如何在内存中找到struct Student的第一个元素呢?

最佳答案

您所拥有的是一种拥有灵活数组成员的古老方法,这在技术上也是未定义的行为。

您正在寻找this .

首先,您需要像这样定义结构(我不知道 Students 之前的 ints 是什么,所以我们就将其称为 id):

typedef struct
{
   int age;
   int phoneNumber;
} Student;

typedef struct
{
  int id;
  Student student;
} StudentAndId;

typedef struct
{
  int id;
  StudentAndId students[];
} People;

请注意 People 内数组的大小不足。现在你这样做:

People *p = malloc(sizeof(People) + sizeof(StudentAndId[NUM_OF_PEOPLE]));

然后您可以访问 p 内的 students 就好像它是一个由 NUM_OF_PEOPLE 元素组成的数组。

<小时/>

请记住使用 C99(或 C11)支持进行编译。对于 gcc,这将是 -std=c99-std=gnu99

关于c - C语言中如何分配不同类型的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22694865/

相关文章:

c - 随机函数的错误

arrays - 从一点在矩阵上的螺旋循环

mysql - 向上指望积极变化,向下指望负面变化

c - 为什么我会收到此错误(指向错误的指针)

c - 如果有的话,编译器什么时候会在指针取消引用优化方面保持保守?

c++ - 基于双向链表的双端队列实现不起作用

c - linux/init.h : No such file or directory

c++ - C/C++ 编译器如何处理具有不同值范围的类型之间的类型转换?

arrays - Swift HTTP POST 二维数组

c - 数组地址和数组本身有什么区别吗?